[Kotlin] Destructuring and ComponentN functions

For data class, you can get 'copy' method, and also destructing:

data class Customer (val name: String, val address: String, var age: Int) {
    // if we don't want to pass in the address
    constructor(name: String, age: Int) : this(name, "", age) // secondary constructor must call primary constructor
}

fun main(args: Array<String>) {
    val c1 = Customer("Wan", 30)
    val (name, address, age) = c1 // you can only get destructing from data class
    println(age) // 30

    val c2 = c1.copy(name="Zhen")
    println(c2.name) // Zhen
}

If you also want to get destructuring from normal class, you can use 'componentN':

class AlternativeCustomer (val name: String, var age: Int) {
    var address: String

    // init will run whenever primary constructor run
    init {
        address = ""
    }

    constructor(name: String, address: String, age: Int): this(name, age) {
        this.address = address
    }

    operator fun component1() = name
    operator fun component2() = age
}

fun main(args: Array<String>) {

    val c3 = AlternativeCustomer("Tian", 23)
    val(n, ag) = c3
    println(n) // Tian
    println(age) // 30
}
原文地址:https://www.cnblogs.com/Answer1215/p/13885908.html