Reputation: 26054
I have a data class MyDataClass
:
data class MyDataClass(val a: Int, val b: Int)
and a class MyClass
with two properties. I want to destructure an instance of MyDataClass
, so a
and b
are assigned to MyClass
properties, instead of declare new variables:
class MyClass {
val a: Int
val b: Int
init {
val mdc = MyDataClass(1, 4)
(a, b) = mdc //error
}
}
Upvotes: 6
Views: 2224
Reputation: 5247
Although destructuring declaration are only allowed for local you can still do something like this
class MyClass {
val a: Int
val b: Int
init {
val (a, b) = MyDataClass(1, 4)
this.a = a
this.b = b
}
}
Upvotes: 4
Reputation: 10047
No, destructuring declarations are only allowed for local variables and lambda parameters.
Also, they are only used to create multiple local variables at once. So val (a, b) = mdc
is allowed, but
(a, b) = mdc
is invalid syntax, even if a
and b
are not properties.
Upvotes: 9