内联RowMapper <t>调用JdbcTemplate.query(String !, RowMapper <t!> !, vararg Any!)

时间:2019-02-25 21:48:45

标签: kotlin spring-jdbc

我无法让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!>!

1 个答案:

答案 0 :(得分:1)

您可以通过说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