[英]varargs to map in Kotlin
I use NamedParameterJdbcTemplate in my project and pass parameters this way: 我在项目中使用NamedParameterJdbcTemplate并通过以下方式传递参数:
MapSqlParameterSource(mapOf(
"userId" to userId,
"count" to count
))
I don't want to write the first line all the time and I want to create my own function that will take pairs of string-to-any values: 我不想一直写第一行,我想创建自己的函数,该函数将成对的字符串到任意值:
params(
"userId" to userId,
"count" to count
)
But when I try to implement it I have issues with generics (I don't post the error description here): 但是当我尝试实现它时,我遇到了泛型问题(我不在此处发布错误描述):
fun params(vararg pairs: Pair<String, Any>) = MapSqlParameterSource(mapOf(pairs))
Could you please advice on the correct implementation? 您能为正确的实施提供建议吗?
mapOf
has 3 implementations: taking nothing, taking 1 pair and taking a vararg of pairs. mapOf
具有3种实现:不采取任何措施,采取1对和采取vararg对。
Since pairs
in your code is actually Array<Pair<String, Any>>
there is no matching implementation of mapOf
to call. 由于代码中的pairs
实际上是Array<Pair<String, Any>>
,因此没有匹配的mapOf
实现要调用。 This is due to the fact that varargs as java implements them are ambiguous in certain cases so Kotlin requires explicit arguments. 这是由于这样的事实:在某些情况下,作为Java实现的varargs在某些情况下是模棱两可的,因此Kotlin需要明确的参数。
To make it work use the "spread" operator to indicate the vararg method should be used. 要使其工作,请使用“ spread”运算符来指示应使用vararg方法。 ( https://kotlinlang.org/docs/reference/functions.html#variable-number-of-arguments-varargs ) ( https://kotlinlang.org/docs/reference/functions.html#variable-number-of-arguments-varargs )
fun params(vararg pairs: Pair<String, Any>) = MapSqlParameterSource(mapOf(*pairs))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.