Is it possible to implement individual destructuring for a non-data class in Kotlin?

In Kotlin data classes, they can be degraded as follows:

fun main(args: Array<String>) {
    val thing = Stuff(1, "Hi", true)
    val(thing1, thing2, thing3) = thing

    println(thing1)
}

data class Stuff(val thing1: Int, val thing2: String, val thing3: Boolean)

I might have read documents incorrectly, or maybe I just couldn’t find an example, but I'm looking for a way to implement custom destructuring classes without data. Is this possible in Kotlin?

+4
source share
2 answers

I managed to do this work as follows:

fun main(args : Array<String>) {
    val person = Person("first", "last")
    val(param1, param2) = person
    println(param1)
    println(param2)
}

class Person(val firstName: String, val lastName: String) {
    operator fun component1() = firstName
    operator fun component2() = lastName
}
+4
source

Destructuring is accomplished by calling functions component1, component2, component3etc., in the case of destructurized instance.

-, , . operator, , , .

, .

:

class Result(val e: Exception?) {
    val hasFailed = e != null

    operator fun component1(): Exception? = e
    operator fun component2(): Boolean = hasFailed
}

val (e, hasFailed) = Result(RuntimeException())
+7

All Articles