多路赋值
Groovy 1.6只增加了一种语法来同时定义多个变量并为其赋值:
1 def (a, b) = [1, 2]
2
3 assert a == 1
4
5 assert b == 2
2
3 assert a == 1
4
5 assert b == 2
返回经纬度坐标的方法或许更有实际意义。如果使用带有两个元素的列表来表示坐标,那么你可以通过如下手段轻松获取每个元素:
1
2
3 def geocode(String location) {
4
5 // implementation returns [48.824068, 2.531733] for Paris, France
6
7 }
8
9 def (lat, long) = geocode("Paris, France")
10
11 assert lat == 48.824068
12
13 assert long == 2.531733
14
15
2
3 def geocode(String location) {
4
5 // implementation returns [48.824068, 2.531733] for Paris, France
6
7 }
8
9 def (lat, long) = geocode("Paris, France")
10
11 assert lat == 48.824068
12
13 assert long == 2.531733
14
15
还可以同时定义变量的类型,如下所示:
1 def (int i, String s) = [1, 'Groovy']
2
3 assert i == 1
4
5 assert s == 'Groovy'
6
2
3 assert i == 1
4
5 assert s == 'Groovy'
6
赋值时无需使用def关键字(前提是变量已经定义好了):
1 def firstname, lastname
2
3 (firstname, lastname) = "Guillaume Laforge".tokenize()
4
5 assert firstname == "Guillaume"
6
7 assert lastname == "Laforge"
2
3 (firstname, lastname) = "Guillaume Laforge".tokenize()
4
5 assert firstname == "Guillaume"
6
7 assert lastname == "Laforge"
如果等号右边列表中的元素个数超过了左边的变量个数,那么只有前面的元素会被赋给左边的变量(自动忽略掉超出的元素——译者注)。如果元素个数少于变量个数,那么多出的变量将被赋为null。
下面的代码展示了变量个数多于列表元素的情况,这里的c被赋为null:
1 def elements = [1, 2]
2
3 def (a, b, c) = elements
4
5 assert a == 1
6
7 assert b == 2
8
9 assert c == null
2
3 def (a, b, c) = elements
4
5 assert a == 1
6
7 assert b == 2
8
9 assert c == null
下面的代码展示了变量个数少于列表元素的情况:
1 def elements = [1, 2, 3, 4]
2
3 def (a, b, c) = elements
4
5 assert a == 1
6
7 assert b == 2
8
9 assert c == 3
2
3 def (a, b, c) = elements
4
5 assert a == 1
6
7 assert b == 2
8
9 assert c == 3
这里我们可以联想到在学校中学到的标准数字交互程序,通过多路赋值可以轻松实现这个功能:
1 // given those two variables
2
3 def a = 1, b = 2
4
5 // swap variables with a list
6
7 (a, b) = [b, a]
8
9 assert a == 2
10
11 assert b == 1
2
3 def a = 1, b = 2
4
5 // swap variables with a list
6
7 (a, b) = [b, a]
8
9 assert a == 2
10
11 assert b == 1