kotlin 解构声明

将对象解构成多个变量,使用起来更加方便。

声明data class

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

使用

        val person = Person("zhangsan", 15, "1")
        val (name, age, gener) = person
        Toast.makeText(this, name, Toast.LENGTH_SHORT).show()

多余变量用不到可以用下划线省略

        val (name, _, _) = person

data class,编译器帮忙生成了componentN函数。

去掉关键字data,自己实现componentN函数也是一样的。

class Person(var name: String, var age: Int, var gender: String) {
    operator fun component1() = name
    
    operator fun component2() = age
    
    operator fun component3() = gender
}

迭代集合更为方便

        val list = mutableListOf<Person>()
        for (i in 0 until 100){
            list.add(Person("zhangsan", i, "1"))
        }
        for ((name, age, gender) in list){

        }

是不是有点熟悉,Map就是这么迭代的

        val map = mutableMapOf<String, Person>()

        for ((key, value) in map) {

        }

点进key,value看一下

public inline operator fun <K, V> Map.Entry<K, V>.component1(): K = key

public inline operator fun <K, V> Map.Entry<K, V>.component2(): V = value

果不其然Map.Entry添加了两个扩展函数