function omelette(... args) { // ❌ Old Way const egg = args[0]; const cheese = args[1]; // ✅ Better Way with Destructuring const [egg, cheese] = args; } omelette('🥚', '🧀'); Breaking down the code.
Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that's more convenient. Destructuring also works great with complex functions that have a lot of parameters, default values, and so on.
Destructuring in JavaScript is used to unpack or segregate values from arrays or properties from object literals into distinct variables, thus it allows us to access only the values required.
Nested Object and Array DestructuringYou can destructure as deeply as you like: As you can see, keys a , b , and c are not implicitly defined, even though we pulled out nested values, firstElemOfC and remainingElementsOfC , from the array at c .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With