函数参数类型匹配问题
IntelliJ向我抛出以下错误,但是我可以告诉,没有任何问题。
最小的例子
import org.springframework.jdbc.core.JdbcTemplate // ... var jdbcTemplate: JdbcTemplate? = null // ... relying on dependency injection from Spring if (jdbcTemplate == null) { throw RuntimeException("jdbcTemplate not injected correctly") } jdbcTemplate.execute("DROP TABLE customers IF EXISTS")
该函数有三个实现。 其中一个接受一个String
。 字符串就是我所给的。 那么到底是什么?
我努力了:
- 使缓存无效并重新启动IntelloJ
- 通过
./gradlew build
+
:compileKotlin e: /home/ruben/workspace/campingmanager/src/main/kotlin/hello/Application.kt: (27, 22): None of the following functions can be called with the arguments supplied: public open fun execute(sql: String!): Unit defined in org.springframework.jdbc.core.JdbcTemplate public open fun <T : Any!> execute(action: ConnectionCallback<(???..???)>!): (???..???) defined in org.springframework.jdbc.core.JdbcTemplate public open fun <T : Any!> execute(action: StatementCallback<(???..???)>!): (???..???) defined in org.springframework.jdbc.core.JdbcTemplate e: /home/ruben/workspace/campingmanager/src/main/kotlin/hello/Application.kt: (28, 22): None of the following functions can be called with the arguments supplied: public open fun execute(sql: String!): Unit defined in org.springframework.jdbc.core.JdbcTemplate public open fun <T : Any!> execute(action: ConnectionCallback<(???..???)>!): (???..???) defined in org.springframework.jdbc.core.JdbcTemplate public open fun <T : Any!> execute(action: StatementCallback<(???..???)>!): (???..???) defined in org.springframework.jdbc.core.JdbcTemplate :compileKotlin FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':compileKotlin'. > Compilation error. See log for more details * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. BUILD FAILED Total time: 8.113 secs
- 获取最新的Kotlin版本1.0.2-1
Kotlin版本 :org.jetbrains.kotlin:kotlin-stdlib:1.0.2
Kotlin插件版本 :1.0.2-1-release-IJ145-20
IntelliJ版本 :2016.1.3
这里的问题是在jdbcTemplate
– 它可以是空的,因为它可以从其他线程更改。 要修复编译错误,您应该将您的调用替换为: jdbcTemplate!!.execute("DROP TABLE customers IF EXISTS")
。
关于不清楚的错误信息有一个问题: KT-11119 。
在这种情况下使用lateinit
也是一个好主意。 (更多信息请参阅文档 。)
检查!!
丑陋的,而是我建议这两种方法。
使用为DI框架专门添加的lateinit
class Database { @Autowired private lateinit var jdbcTemplate: JdbcTemplate; fun initCustomerDatabase() { jdbcTemplate.execute("DROP TABLE customers IF EXISTS") } }
缺点:在jdbcTemplate
上的每个调用上进行额外的运行时检查。 缺点: jdbcTemplate
是可变的。
使用构造函数注入
class Database @Autowired constructor(val jdbcTemplate: JdbcTemplate) { fun initCustomerDatabase() { jdbcTemplate.execute("DROP TABLE customers IF EXISTS") } }
优点: jdbcTemplate
一成不变优点:没有运行时检查。
在4.3版本中,即使不使用@Autowired constructor
,也可以编写如下代码:
class Database(val jdbcTemplate: JdbcTemplate) { fun initCustomerDatabase() { jdbcTemplate.execute("DROP TABLE customers IF EXISTS") } }
我个人使用构造函数注入,因为它是非常有用的测试。