zoukankan      html  css  js  c++  java
  • [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
    }
  • 相关阅读:
    DS博客作业02--栈和队列
    DS博客作业02--线性表
    c博客06-结构
    c博客作业05--指针
    C博客作业04--数组
    博客作业03-函数
    循环结构
    c博客作业01--分支、顺序结构
    我的第一篇博客
    Macos安装JDK1.8
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13885908.html
Copyright © 2011-2022 走看看