I have a class Person
:
class Person(val name: String, val age: Int)
I want to use Destructuring declaration with Parent
like this:
val (name, age) = Person("name", 22)
but I get this error:
Destructuring declaration initializer of type Person must have a 'component1()' function Destructuring declaration initializer of type Person must have a 'component2()' function
This syntax is called a destructuring declaration. A destructuring declaration creates multiple variables at once. You have declared two new variables: name and age, and can use them independently: Copied! A destructuring declaration is compiled down to the following code: Copied!
Object destructuring Basic assignment Assignment without declaration Assigning to new variable names Default values Assigning to new variables names and providing default values Unpacking fields from objects passed as function parameter Setting a function parameter's default value Nested object and array destructuring
Kotlin provides the programmer with a unique way to work with instances of a class, in the form of destructuring declarations. A destructuring declaration is the one that creates and initializes multiple variables at once. These multiple variables correspond to the properties of a class that are associated with an instance.
So you can freely use destructuring declarations in for -loops with maps (as well as collections of data class instances or similar). If you don't need a variable in the destructuring declaration, you can place an underscore instead of its name:
The easiest way to solve this problem is to use a data class since data classes automatically declare componentN()
functions (see the docs).
data class Person(val name: String, val age: Int)
val (name, age) = Person("name", 22) // OK
Sometimes you might not have access to the source code of a class you want to allow destructuring, so if for any reasons you are not allowed to use data classes, you can provide the componentX
functions (component1
and component2
in this case) by using extension functions.
operator fun Person.component1() = name
operator fun Person.component2() = age
We need to declare Person
as data class.
data class Person(val name: String, val age: Int)
it wasn't very clear in the docs but for official ref:
https://kotlinlang.org/docs/reference/multi-declarations.html#example-returning-two-values-from-a-function
from Marko Topolnik comment:
if for some reason someone can't use data class it's not mandatory. You can declare the functions component1()
and component2()
in any class.
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