Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

varargs to map in Kotlin

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?

like image 968
awfun Avatar asked Jan 04 '23 13:01

awfun


1 Answers

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))

like image 173
Kiskae Avatar answered Jan 08 '23 06:01

Kiskae