Can destructuring be used in function arguments?

Kotlin supports destructuring declarations:

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

This is similar to the unpacked unboxing of Python:

 a, b = (1, 2) 

Python also has a splat / spread statement 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 unzip the structure manually:

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

But this is awkward. Is there any way to make this more elegant? I don’t see anything in the related documents .

+6
source share
3 answers

No, this is only possible for arrays and vararg functions

 val foo = arrayOf(1, 2, 3) val bar = arrayOf(0, *foo, 4) 
+10
source

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

1) the extension operator for arguments without vararg 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:

Destruction for lambda arguments was implemented in Kotlin 1.1.

+8
source

You can define an extension function to propagate Pair arguments. 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)) } 

Prints 3.

0
source

All Articles