解构声明
Kotlin官网:Other-Destructuring Declarations
解构声明可以方便地将一个对象分解成多个变量:
val (name, age) = person
println(name)
println(age)
上例中,解构声明会编译成:
val name = person.component1()
val age = person.component2()
这里的componentN()函数为重载的运算符函数,需要有operator修饰,N为正整数。
解构声明也支持在for循环中使用:
for ((a, b) in collection) { ... }
a和b分别接收collection中元素item的component1()和component2()的返回值。
例1:一个函数,返回两个值
有时一个函数需要返回两个值,例如成对的状态和结果,此时可以返回支持解构声明的类的实例,例如数据类(数据类会由编译器自动生成解构函数)。
标准库中有Pair类实现,当然自己定义一个取个好名字更好。
data class Result(val result: Int, val status: Status)
fun function(...): Result {
// computations
return Result(result, status)
}
// Now, to use this function:
val (result, status) = function(...)
例2:解构声明和Map
遍历Map的理想方式:
for ((key, value) in map) {
// do something with the key and the value
}
要实现这个效果,需要满足:
- 有iterator()函数
- 每个元素含有component1()和component2()函数
标准库中提供了Map的相应扩展函数,可以直接使用解构声明和for循环遍历map:
operator fun <K, V> Map<K, V>.iterator(): Iterator<Map.Entry<K, V>> = entrySet().iterator()
operator fun <K, V> Map.Entry<K, V>.component1() = getKey()
operator fun <K, V> Map.Entry<K, V>.component2() = getValue()
下划线替代未用到的变量(Kotlin1.1后支持)
对于解构声明中不需要的参数,可以使用下划线代替:
val (_, status) = getResult()
这样对于下划线的参数不会调用componentN()函数,直接跳过。
Lambda中的解构(Kotlin1.1后支持)
Lambda的参数也支持解构声明:
map.mapValues { entry -> "${entry.value}!" }
map.mapValues { (key, value) -> "$value!" }
注意区分“多个参数”的“解构声明”的区别,参数没有括号,解构声明有括括号:
{ a -> ... } // 1个参数
{ a, b -> ... } // 2个参数
{ (a, b) -> ... } // 1个解构声明
{ (a, b), c -> ... } // 1个解构声明和1个参数
lambda中的解构声明也支持下划线标明未使用参数:
map.mapValues { (_, value) -> "$value!" }
支持指定类型,可以给解构声明整体指定,也可以单独给解构声明中某一项指定:
map.mapValues { (_, value): Map.Entry<Int, String> -> "$value!" }
map.mapValues { (_, value: String) -> "$value!" }