Kotlin语法(二十)-变形声明(Destructuring Declarations)

         参考原文: http://kotlinlang.org/docs/reference/multi-declarations.html

 

         可以通过下面方式方便的解构(destructure)一个对象到参数组中,如:

data class Person(var name, var age) {
}
//
val person = Person(name="tom ", age=13)
val (name, age) = person

 

         该语法称之为:变形声明(   destructuring declaration)。一次可以创建多个新的变量元素;如上例中,得到“name”和“age”两个新变量元素,可以单独使用它们:

println(name)
println(age)

 

         最后编译成如下代码:

val name = person.component1()
val age = person.component2()

 

         “component1()”和“component2()”函数是Kotlin中公用约定部分(principle of conventions)(其他如操作符“+”,“*”,for循环等)。任何都可以放到变形声明的右边,只要该对象有对应个数的“component”函数。

 

         变形声明(   destructuring declaration)也可以用在循环中,如:

for ((a, b) in collection) { ... }

         变量“a”和“b”的值对应集合元素对应的“component1()”和“component2()”获取的值。

    例子:从函数中返回两个值

         需要从一个函数中返回两个值;比如:一个为结果对象,另一个为状态值;通过创建一个数据类( dataclass)来存储结果:

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(...)

 

         注:数据类会自动生成“componentN()”函数。

         这里也可以使用API提供的标准库类“Pair”,使用“function(...)”返回“Pair<Int, Status>”;这种方式相对于自定义数据类方式,不能再参数名称上直接表达出相关意图。

 

    例子:变形声明和映射表(Maps)

         通过下面方式遍历一个map:

for ((key, value) in map) {
   // do something with the key and the value
}

 

         需要满足下面两个条件:

        Ø  map作为序列,需要提供“iterator()”函数。

        Ø  map的元素需要提供“component1()”和“component2()”函数。

 

        为了方便使用,标准库提供了如下的扩展:

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()











  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值