我在代码中遇到过几次,无法弄清楚这个声明到底是什么。它看起来只是一个变量的集合,但它被传递在一起,就好像它是一个奇异的变量或对象本身,包含了所有3个值。这到底是什么?
def foo(filename) {
// Below you can find an assignment I don't understand:
def (id, company, type) = roo(filename)
AClass.findByStuff(id, company, type)
}
这是Groovy的多重赋值特性。简而言之,它期望右侧的元素集合和括号中的变量列表将列表中的元素分配给左侧的。例如:
def (a, b, c) = [1, 10, 100, 1000]
assert a == 1
assert b == 10
assert c == 100
此赋值防止抛出IndexOutOfBoundsException
,如果左侧的变量数量大于右侧集合中的元素数量,则它只分配null
值,例如:
def (a, b, c) = [1, 10]
assert a == 1
assert b == 10
assert c == null