Kotlin 解构声明

在一些像 Python 的高级语言中,支持 多返回值的,例如 x, y = get_position() 这样操作接收。
而在 Kotlin 中,虽然不支持 多返回值,但有类似的 解构(destructure) 对象功能,叫做 解构声明

(变量1, 变量2, ...) = obj 形式,一次性创建赋值 多个变量。

举例说明:

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

// Person 对象 可以 解构为 几个变量
val (name, age) = person

说明:

解构对象的原理是,只要 实现了 component1() component2()componentN() 函数,就可按顺序 返回 解构的属性值。

而 上面代码,实际是 编译成 了:

name = person.component1()
age = person.component2()
  • data class 会自动实现 compoenntN() 方法。

componentN() 函数

可手动实现 componentN() 函数,必须用 operator 关键字标记函数

举例,实现 解构函数:

operator fun component1(): String {
	return this.name
}

解构使用

1. 可使用标准的 PairTriple 返回 两、三个值
2. 未使用的变量,可用 _ 标记
val (_, status) = getResult()

说明:对于 _ 未使用的变量, componentN() 函数将不会调用,直接跳过

2. map 的 迭代 解构
for ((key, value) in map) {
   // do something with the key and the value
}

说明:

Kotlin 实现了 Entry 的拓展函数 component1() component2() ,支持解构。

4. List 和 Array 解构

Kotlin 列表和数组,也支持解构:

fun getList() = listOf(1, 2, 3, 4)

val (a, b, c, d) = getList()

注意:数组和列表,默认解构最多支持前5个元素

文档

  • Destructuring declarations

你可能感兴趣的:(kotlin,开发语言,android)