Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reassigning Variables via Destructuring

Tags:

kotlin

I love Kotlin's destructuring features, they help me to declutter code and focus on the essential.

I encountered a case for which I could not figure out the correct syntax, how can I reassign variables via destructing?

var (start, end) = startEndDate(198502)

// intellij neither accept this ...
start, end = startEndDate(200137)

// ... nor this
(start, end) = startEndDate(200137)
like image 670
linqu Avatar asked Sep 01 '16 13:09

linqu


People also ask

How do you swap variables using Destructuring assignment?

Destructuring assignment[a, b] = [b, a] is the destructuring assignment that swaps the variables a and b . At the first step, on the right side of the destructuring, a temporary array [b, a] (which evaluates to [2, 1] ) is created. Then the destructuring of the temporary array occurs: [a, b] = [2, 1] .

Does Destructuring create a new variable?

Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables.

Can you Destructure an array?

Using array destructuring on any iterableNon-iterables cannot be destructured as arrays.


1 Answers

From the language perspective, the variables declared in destructuring declaration are just separate independent variables, and at the moment Kotlin doesn't provide a way to assign multiple variables in a single statement.

You can only destructure your expression again and assign the variables one by one:

var (start, end) = startEndDate(198502)

val (newStart, newEnd) = startEndDate(200137)
start = newStart
end = newEnd

If you need to show that these two variables have have some special meaning and should be assigned together, you can declare a local function that reassigns them like this:

var (start, end) = startEndDate(198502)
fun setStartEnd(pair: Pair<SomeType, SomeType>) { start = pair.first; end = pair.second }

setStartEnd(startEndDate(200137))
like image 176
hotkey Avatar answered Sep 29 '22 18:09

hotkey