I use NamedParameterJdbcTemplate in my project and pass parameters this way:
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.
Since pairs
in your code is actually Array<Pair<String, Any>>
there is no matching implementation of mapOf
to call. This is due to the fact that varargs as java implements them are ambiguous in certain cases so Kotlin requires explicit arguments.
To make it work use the "spread" operator to indicate the vararg method should be used. (https://kotlinlang.org/docs/reference/functions.html#variable-number-of-arguments-varargs)
fun params(vararg pairs: Pair<String, Any>) = MapSqlParameterSource(mapOf(*pairs))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With