天天看點

Groovy 程式結構之變量指派

http://www.groovy-lang.org/structure.html

上面是Groovy官網程式結構的位址

1. Multiple assignment

同時多個指派

def (a, b, c) = [10, 20, 'foo']
           

上面的a. b  c是沒有類型的 如果想要給其聲明類型

def (int i, String j) = [10, 'foo']
           

除了上面二種方式,還可以把已經定義的值指派

def nums = [1, 3, 5]
        def a, b, c
        (a, b, c) = nums
           

上面分别給a指派為1 b指派為3 5指派為5. 如果聲明的變量要指派的個數大于數組的長度 name最後一個值為null

class ListStudy {
    static void main(String[] args) {
        def nums = [1, 3]
        def a, b, c
        (a, b, c) = nums
        println(a)
        println(b)
        println(c)
    }
}
           

這個時候c就是null

如果是給String變量指派,groovy還提供了一種方式

def (date, month, year) = "15 06 2019".split()
           

2. Overflow and Underflow

翻譯:溢出和下溢

溢出

def (a, b, c) = [1, 2]
           

下溢

def (a, b) = [1, 2, 3]
           

多餘的3會被忽略

3. Object destructuring with multiple assignment

使用多個指派的對象析構

class ListStudy {
    double latitude
    double longitude
    double getAt(int idx) {
        if (idx == 0) latitude
        else if (idx == 1) longitude
        else throw new Exception("Wrong coordinate index, use 0 or 1")
    }
    static void main(String[] args) {
        def coordinates = new ListStudy(latitude: 43.23, longitude: 3.67)
        println(coordinates.getAt(0))
        println(coordinates.getAt(1))
    }
}
           

其實就是給類中的成員變量指派,

繼續閱讀