Home > Software design >  Passing a Tuple or Triple as parameters in Kotlin
Passing a Tuple or Triple as parameters in Kotlin

Time:10-14

I have a function in Kotlin that is something like this:

fun getSlots(year: Int, month: Int, day: Int) {
    // some magic stuff, for example let's just print it
    print("$year-$month-$day")
}

And I have another function that returns a Triple:

fun myMagicFunction(): Triple<Int, Int, Int> {
    return Triple(2020, 1, 1)
}

I would like to call to the first function getSlots, using the return value of the second function myMagicFunction, without having to extract the members from the triple and pass them one by one. Something that in Python for example is possible by doing func(*args), but I don't know if it is possible in Kotlin.

Is it possible in Kotlin or do I have to go the slow way with this situation? Assume that modifying the previous two functions to return something else is not an option.

CodePudding user response:

I can't find any simple way (hopefully it will be available some day in kotlin). However you can write some helper infix function like this:

infix fun  <T, U, S, V> KFunction3<T, U, S, V>.callWith(arguments: Triple<T, U, S>) : V = this.call(*arguments.toList().toTypedArray())

and then just simply call it:

::getSlots callWith myMagicFunction()

Of course you can add another one for Pair:

infix fun  <T, U, V> KFunction2<T, U, V>.callWith(arguments: Pair<T, U>) : V = this.call(*arguments.toList().toTypedArray())

CodePudding user response:

Kotlin also has a spread operator (func(*args)), but currently it works only if the argument of func is declared as vararg (to avoid runtime exception if the size of args is not the same as func arity).

Just add one more code line with destructing declaration:

val (year, month, day) = myMagicFunction()
getSlots(year, month, day)
  • Related