我无法将varargJdbcTemplate.query(String!, RowMapper<T!>!, vararg Any!)一起使用。如果我关闭可变参数,它似乎可以工作。例如:

这有效:

fun translates(field: String) = template.query("SELECT key, value FROM table", {
    rs: ResultSet, _: Int -> Pair(rs.getString("key"), rs.getString("value"))
})

或这可行:
fun translates(field: String) = template.query("SELECT key, value FROM table") {
    rs: ResultSet, _: Int -> Pair(rs.getString("key"), rs.getString("value"))
}

但这不起作用(我在函数调用的末尾添加了, field,它应该与query(String!, RowMapper<T!>!, vararg Any!)函数匹配):
fun translates(field: String) = template.query("SELECT key, value FROM table WHERE field = ?", {
    rs: ResultSet, _: Int -> Pair(rs.getString("key"), rs.getString("value"))
}, field)

这是错误消息的相关部分:
query(String!, RowMapper<T!>!, vararg Any!)
  where T cannot be inferred for
  fun <T : Any!> query(sql: String!, rowMapper: RowMapper<T!>!, vararg args: Any!): (Mutable)List<T!>!

最佳答案

您可以通过说RowMapper { .. }来帮助编译器推断中间的lambda类型:

fun translates(field: String) = template.query("SELECT key, value FROM table", RowMapper { rs: ResultSet, _: Int ->
    Pair(rs.getString("key"), rs.getString("value"))
  }, field)

添加RowMapper使Kotlin SAM正常工作
https://kotlinlang.org/docs/reference/java-interop.html

关于kotlin - 内联RowMapper <T>调用JdbcTemplate.query(String !, RowMapper <T!> !, vararg Any!),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54875181/

10-10 16:29