Kotlin 笔记 3.8:对象结构

在 Kotlin 中,支持将一个对象解构成变量:

var (name,age,school) = person

上面的代码相当于将 person 对象的三个属性分别赋值给了 name、age 和 school 三个变量,这三个变量可以直接使用:

    val (name, age, school) = person
    println("name = $name    age = $age   school = $school")

看到这里肯定会一脸懵逼,咋就赋值给了那三个变量了呢?Kotlin 提供了一个 componentX 的方法,需要我们在类中定义:

fun main() {
    var person = Person("张三", 20, "一中")
    //将 person 对象结构给两个变量
    val (name, age) = person
    println("name = $name    age = $age")
}


class Person(var name: String, var age: Int, var school: String) {
    operator fun component1(): String {
        return this.name
    }

    operator fun component2(): Int {
        return this.age
    }

    operator fun component3(): String {
        return this.school
    }
}

可见,componentX 方法需要关键字 operator 来修饰,有时候我们需要结构对象的后面几个对象,那么前面的就可以使用 _ 来代替:

fun main() {
    var person = Person("张三", 20, "一中")
    //将 person 对象结构给两个变量
    val (name, age) = person
    val (_, age2, school) = person
    println("name = $name    age = $age")
    println("name = $name    age2 = $age2    school = $school")
}


class Person(var name: String, var age: Int, var school: String) {
    operator fun component1(): String {
        return this.name
    }

    operator fun component2(): Int {
        return this.age
    }

    operator fun component3(): String {
        return this.school
    }
}
//输出结果:
name = 张三    age = 20
name = 张三    age2 = 20    school = 一中

对象解构的高级用法

譬如有这样一个需求:通过 ID,去获取用户的姓名和年龄:

fun main() {
    var person = getPerson("123123")
    var (name, age) = person
    println("name = $name      age = $age")
}

data class Person(var name: String, var age: Int) {

}

fun getPerson(id: String): Person {
    //通过数据库查询,获取到该 Id 匹配的姓名和年龄
    return Person("张三", 20)
}
//输出结果:name = 张三      age = 20

Person 类我们声明为数据类,数据类会自动生成 componentX 函数,这样是不是方便很多?