天天看点

Kotlin学习篇(1)Destructuring Declarations

Destructuring Declarations

这个概念翻译过来就是解构声明,读起来比较拗口,

那么究竟什么意思呢?我们一起看一下官方的解释

val (name, age) = person 
This syntax is called a destructuring declaration. A destructuring declaration creates multiple variables at once. We have declared two new variables: name and age, and can use them independently:
           

有时候,当我们将一个对象拆解成一系列变量是非常方便的,例如:

val (name,age) = person

这种语法就叫做解构声明。解构声明可以一次创建多个变量。上面这个例子,我们就声明了两个新的变量:name 和 age,并且可以分别使用它们。

说白了,这里是对于java中多个构造函数的优化,记得view 的默认构造方法就有3个,而在这里,是分开的,独立的。

再来看一个实际的例子:

从一个函数返回多个值

class MyDate(val year: Int, val month: Int, val dayOfMonth: Int){
    operator fun component1():Int{
        return year
    }
    operator fun component2():Int{
        return month
    }
    operator fun component3():Int{
        return dayOfMonth
    }
}

fun isLeapDay(date: MyDate): Boolean {
    val (year, month, dayOfMonth) = date
    // 29 February of a leap year
    return year %  ==  && month ==  && dayOfMonth == 
}
           

在类MyDate中申明了3个组件,通过解构申明,在isLeapDay函数中,一次性返回MyDate的三个函数。无需考虑使用set、get方法。

调用方式如下:

fun testIsLeapDay() {
        assertTrue(isLeapDay(MyDate(, , )))
        assertFalse(isLeapDay(MyDate(, , )))
    }