20

Kotlin supports destructuring declarations:

val (a, b) = Pair(1,2)

This is similar to Python's iterable unpacking:

a, b = (1, 2)

Python also has a splat/spread operator that allows you to perform a similar operation with function arguments:

def f(a, b): pass
pair = (1,2)
f(*pair)

Does kotlin have a similar ability? Obviously, you can unpack the structure manually:

f(pair.component1(), pair.component2())

But that's clunky. Is there a way to do that more elegantly? I don't see anything in the docs on the subject.

3 Answers 3

19

No, this is possible only for arrays and vararg-functions

val foo = arrayOf(1, 2, 3)
val bar = arrayOf(0, *foo, 4)
Sign up to request clarification or add additional context in comments.

1 Comment

That's too bad. Strange that the spread operator exists in such a limited fashion.
15

Adding to the answer by @Ivan, here are the related issues:

1) spread operator for non-vararg arguments in function calls:

https://youtrack.jetbrains.com/issue/KT-6732

2) destructuring for lambda arguments:

https://youtrack.jetbrains.com/issue/KT-5828

You can vote for them.


Update:

Destructuring for lambda arguments was implemented in Kotlin 1.1.

Comments

5

You could define an extension function to spread the arguments of the Pair. Like this:

fun <A, B, R> Pair<A, B>.spread(f: (A, B) -> R) = f(first, second)

fun add(a: Int, b: Int) = a + b

fun main(args: Array<String>) {
    println(Pair(1, 2).spread(::add))
}

This prints 3.

1 Comment

fun <A, B, R> ((A, B) -> R).spread(p:Pair<A, B>) = invoke(p.first, p.second) to pass function which take single pair arg, but actualy two ::myFunc::spread

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.