[Kotlin] Destructuring and ComponentN functions
Kotlin and Functions
2023-09-14 09:00:46 时间
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 }
相关文章
- kotlin中Activity跳转
- android Kotlin int类型和Long类型转换
- Kotlin Flow响应式编程,基础知识入门
- 【Kotlin】Kotlin 类的继承 三 ( super 关键字使用 | super@ 外部调用父类方法 | 子类选择性调用 父类 / 接口 方法 super )
- 【错误记录】Android Studio 编译报错 ( kotlin library {0} was compiled with a newer kotlin compiler and not b )
- 【错误记录】Kotlin 报错 ( Some kotlin libraries attached to this project were compiled with a newer kotlin )
- 【Kotlin 协程】协程底层实现 ② ( 协程调度器 | 协程任务泄漏 | 结构化并发 )
- 【Kotlin 协程】协程启动 ⑥ ( 协程生命周期状态 | 新创建 New | 活跃 Active | 完成中 Completing | 已完成 Completed | 取消中 | 已取消 )
- 【Kotlin 协程】Flow 操作符 ① ( 过渡操作符 | map 操作符 | transform 操作符 | 限长操作符 | take 操作符 )
- 【Kotlin】函数 ⑥ ( 函数参数为 Lambda 表达式 | Lambda 表达式作为参数的简略写法 | 唯一参数的简略写法 | 最后一个参数的简略写法 )
- 【Kotlin】空安全 ⑤ ( 异常处理 | 捕获并处理异常 | 抛出自定义异常 )
- 【Kotlin】标准库函数 ② ( run 标准库函数 | run 函数传入 Lambda 表达式作为参数 | run 函数传入函数引用作为参数 )
- 17 位谷歌 Android 开发专家是如何看待 Kotlin 的详解编程语言
- 深入探究Mysql中IN与AND逻辑运算的应用(mysql中in与and)
- MySQL中AND的使用方法及含义解析(mysql中and的含义)
- and的区别Oracle数据库中的OR与AND的差异(oracle中or和)