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)
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] .
Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables.
Using array destructuring on any iterableNon-iterables cannot be destructured as arrays.
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))
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