Search code examples
kotlin

Can't use Destructuring declaration


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


Solution

  • 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.