解构声明(Destructuring Declarations):个人理解,是一种通过方便的方法得到一个对象的成员变量
普通应用
我们在一个文件中定义一个Person类
data class Person(val name: String, val age: Int)
我们可以通过简单的语法获得这个类的name和age属性
val (name, age) = Person("tom", 11)
println(name)
println(age)
属性结果是:
I/System.out: tom
I/System.out: 11
上面的Person是数据类(data class)当我们定义一个普通的类,看看
class Dog(val name: String, val age: Int)
我们发现不能简单的通过下面的方法获取name和age的值
val (nameDog, ageDog) = Dog("James", 5)
为什么数据类可以,普通类就不可以呢?
因为数据类帮我们实现了解构声明需要的componentN方法这个N可以是1或者2等.
我们重新定义Dog类:
class Dog(val name: String, val age: Int) {
operator fun component1() = name
operator fun component2() = age
}
val (nameDog, ageDog) = Dog("James", 5)
println(nameDog)
println(ageDog)
上面的代码打印输出:
I/System.out: James
I/System.out: 5
方法返回两个值
不解释,看代码
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(...)
解构声明和Map
通过解构声明变量Map,打印key和value
val map = mapOf<Int, String>(1 to "one", 2 to "two", 3 to "three")
for ((a, b) in map) {
print("$a-")
println(b)
}
输出:
I/System.out: 1-one
I/System.out: 2-two
I/System.out: 3-three
转换一个Map的value值
val map = mapOf<Int, String>(1 to "one", 2 to "two", 3 to "three")
val map2 = map.mapValues { (key, value) -> "android_$value" }
for ((a, b) in map2) {
print("$a-")
println(b)
}
输出:
I/System.out: 1-android_one
I/System.out: 2-android_two
I/System.out: 3-android_three