Since Groovy 1.6 we can define and assign values to several variables
at once. This is especially useful when a method returns multiple
values and we want to assign them to separate variables.
<!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
-->// Assign and declare variables.
def (username, email) = ['mrhaki', 'email@host.com']
assert 'mrhaki' == username
assert 'email@host.com' == email
// We can assign later than the definition of the variables.
int housenr
String streetname
(streetname, housenr) = ['Old Street', 42]
assert 42 == housenr
assert 'Old Street' == streetname
// Return value of method can be assigned to multiple variables.
def iAmHere() {
[29.20090, 12.90391]
}
def (coordX, coordY) = iAmHere()
assert coordX == 29.20090
assert coordY == 12.90391
// More values than variables: extra values are ignored.
def (a, b, c) = ['a', 'b', 'c', 'd']
assert 'a' == a
assert 'b' == b
assert 'c' == c
// Less values than variables: variable is not set.
def (x, y, z) = [100, 200]
assert 100 == x
assert 200 == y
assert !z
def (username, email) = ['mrhaki', 'email@host.com']
assert 'mrhaki' == username
assert 'email@host.com' == email
// We can assign later than the definition of the variables.
int housenr
String streetname
(streetname, housenr) = ['Old Street', 42]
assert 42 == housenr
assert 'Old Street' == streetname
// Return value of method can be assigned to multiple variables.
def iAmHere() {
[29.20090, 12.90391]
}
def (coordX, coordY) = iAmHere()
assert coordX == 29.20090
assert coordY == 12.90391
// More values than variables: extra values are ignored.
def (a, b, c) = ['a', 'b', 'c', 'd']
assert 'a' == a
assert 'b' == b
assert 'c' == c
// Less values than variables: variable is not set.
def (x, y, z) = [100, 200]
assert 100 == x
assert 200 == y
assert !z
本文介绍Groovy中定义多个变量并一次性赋值的方法,包括如何使用方法返回多个值并将其分配给多个变量。同时展示了在不同场景下多变量赋值的特点。
1908

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



