将一个对象解构成多个变量
一、解构声明
data class Person(val name: String, val age: Int)
fun main() {
val person = Person("wmj", 25)
// 解构声明
val (name, age) = person
// 等价于
// val name = person.name
// val age = person.age
}
解构声明会被编译成如下代码
val name = person.component1()
val age = person.component2()
使用解构声明时,对象需要提供 componentN
函数,componentN
函数需要用 operator
关键字修饰。data class
默认声明了 componentN
函数
class Student(val name: String, val age: Int){
operator fun component1(): String{
return name
}
operator fun component2(): Int{
return age
}
}
fun main() {
val (name, age) = Student("wmj",25)
}
二、解构声明例子
List
val list = listOf(Person("wmj", 25))
for ((name, age) in list) {
}
// kotlin1.1 以后,用下划线替换不使用的属性
for ((_, age) in list) {
}
Map
val map = mapOf(Pair("key", "value"))
for ((key, value) in map) {
}
Lambda
map.mapValues { (key, value) -> key + value }
网友评论