Kotlin: Idiomatic Call Method (Int, Int) & # 8594; Int with a pair <Int, Int>?
fun sum(a: Int, b: Int) = a + b
val x = 1.to(2)
I'm looking for:
sum.tupled(x), orsum(*x)
Of course, none of the above compilations with Kotlin 1.1.3-2. So what am I stuck with sum(x.first, x.second)?
Edit
Summarizing the useful answers, I think this is now the closest:
fun <P1, P2, R> Function2<P1,P2,R>.tupled(x: Pair<P1, P2>): R = invoke(x.first, x.second)
+4
3 answers
After you find out about your needs, I think you donβt need overload / extension functions at all, just using KCallable # call , for example:
val x = arrayOf(1, 2)
// v--- top-level functions
val result:Int = ::sum.call(*x)
// v--- member-level functions
val result:Int = this::sum.call(*x)
You can also overload a function sumin Kotlin in the same way as Java, for example:
sum(1 to 2)
sum(*intArrayOf(1, 2))
fun sum(tuple: Pair<Int, Int>) = sum(tuple.first, tuple.second)
fun sum(vararg pair: Int) = sum(pair[0], pair[1])
For sum.tupled(x)you can write an extension function, for example:
val sum: (Int, Int) -> Int = ::sum // top-level function
//OR
val sum:(Int, Int)->Int = this::sum // member scope function
// the final form is what you want
// v
val result:Int = sum.tupled(1 to 2)
fun <T1,T2,R> Function2<T1,T2,R>.tupled(x:Pair<T1,T2>):R = invoke(x.first,x.second)
+1