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))
}
}
其实就是给类中的成员变量赋值,
本文介绍了Groovy程序结构中关于变量赋值的细节,包括多重赋值、类型声明、溢出与下溢处理以及对象析构。在多重赋值时,Groovy允许同时为多个变量赋值,如果赋值数量大于变量数量,多余值将被忽略,少于变量数量则未赋值的变量为null。此外,Groovy还支持通过对象析构来便捷地为类成员变量赋值。
2042

被折叠的 条评论
为什么被折叠?



