kotlin解构声明

深入学习Kotlin基础知识
2022-07-01 18:35 · 阅读时长3分钟
小课

解构申明可以很方便的将一个对象拆解成多个独立的变量,很多常用的编程语言都已经支持这个特性,比如JavasSript、Python等。解构申明在很多情况下可以简化代码,比如方法返回、集合遍历。

data class Person(
    val id: Int,
    val name: String,
    val age: Int
)

val person = Person(1, "Jon Snow", 20)
val (id, name, age) = person
println("$id $name $age")// 1, Jon Snow, 20

通过解构申明,我们可以一次性将id,name,age等属性值从person对象中取出来,但是需要注意的是,它并不能像JavaScript中那样根据名称只取其中某几个属性。如果我们需要取其中几个属性,需要用_符号进行占位,比如

val (_, name, age) = person
println("$name $age")// Jon Snow, 20

看上去很神奇,它是怎么做到的呢?其实这都是kotlin编译器的功劳,上面的代码经过编译后转化成了下面这样。

Person person = new Person(1, "Jon Snow", 20);
String name = person.component2();
int age = person.component3();
System.out.println(name + ' ' + age);

可以看出来data class在编译之后生成了componentX方法,用于实现解构声明。

函数返回值

比如上面的Person,返回可以直接用解构声明多个变量来接收返回值。

fun getPersonInfo() = Person(2, "Ned Stark", 45)
val (id, name, age) = getPersonInfo()

或返回两个值

fun request(): Pair<Int, String> {
    // ...
    return Pair(1, "success")
}
val (result, status) = request()
Map遍历
val map = mapOf(Pair("key1", "value1"), Pair("key2", "value2"))
for ((key, value) in map) {
    println("$key $value")
}
//key1 value1
//key2 value2

使用for loop遍历map返回的是Map.Entry<K, V>类型,kotlin为它添加了扩展方法component1component2

operator fun <K, V> Map.Entry<K, V>.component1() = getKey()
operator fun <K, V> Map.Entry<K, V>.component2() = getValue()
kotlin解构声明