Can't use Destructuring declaration
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.
It's very helpful if you simply let the IDE do some work for you. Here are the suggestions given by IntelliJ IDEA that help to fix the error:
It basically lists all alternatives: data
class is probably the easiest one. You can also create the corresponding componentX
functions manually, which are otherwise automatically generated for data
classes. In this SO thread, I gave some information on this kind of function.
As to your example, I'll show how to provide the componentX
functions by using extension functions. This approach is especially useful whenever you're working with classes that you cannot modify yourself. It's that simple:
private operator fun Person.component1() = name
private operator fun Person.component2() = age