天天看點

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