https://kotlinlang.org logo
Title
d

Draget

12/13/2020, 7:41 PM
Can I deconstruct variables while assigning them? Works:
var (a ,b) = somethingReturningAPair()
But what does not work:
var a: Int
var b: Int
(a, b) = somethingReturningAPair()
Or does it only work when initalizing variables?
a

Aleksander Ściborek

12/13/2020, 7:58 PM
You have to initialize variables as they are not nullable
l

lorefnon

12/13/2020, 8:45 PM
Yeah, kotlin supports destructuring only in declarations (including for loops and lambdas) so you can't destructure into pre-existing variables. However it is convenient to use it with
let
, so you can
var a: Int = ... // some number
var b: Int = ... // some number

somethingReturningAPair().let { (a, b) -> 
    // a,b shadowed here 
}
v

Vampire

12/13/2020, 11:38 PM