Reusing vars in destructuring declarations

What’s the syntax for reusing vars in destructuring declarations?

var (name, age) = person 
(name, age) = anotherPerson // this doesn't work
1 Like

Destructuring to existing variables is something which isn’t currently supported though I’m hoping that it might be in the future as it was one of the 20 ‘possible future features’ which the Kotlin team put forward for consideration in the recent poll and I personally voted for it.

In the meantime all you can do is either destructure to new variables or try to put repeated code into some sort of loop (or repeat() function) so you can redeclare the same variables each time through the loop.

There’s an open feature request to enable destructuring assignment.

I wasn’t clear whether KT-11362 was advocating adding destructuring assignment or multiple assignment as well.

I’m not a big fan of the latter as it can lead to some confusing code when the variables being assigned to are involved in the expressions on the RHS of the ‘=’ sign.

If we just had destructuring assignment, we’d still be able to swap scalar variables with code such as this:

var a = 1
var b = 2
(a, b) = b to a

The only problem is that you’d be creating an intermediate Pair object so it might not be worth it just to save a couple of lines.