Groovy 中的奇怪定义方法 (def)。看起来像一个没有名字的对象或函数
Strange definition method (def) in Groovy. Looks like an object or function with no name
我在代码中遇到过几次,无法弄清楚这个声明到底是什么。它看起来只是一个变量的集合,但被一起传递,就好像它是某个单一变量或对象本身持有所有 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的multiple assignment feature。简而言之 - 它需要右侧的元素集合和括号中的变量列表,以便将列表中的元素分配给左侧。例如:
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
我在代码中遇到过几次,无法弄清楚这个声明到底是什么。它看起来只是一个变量的集合,但被一起传递,就好像它是某个单一变量或对象本身持有所有 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的multiple assignment feature。简而言之 - 它需要右侧的元素集合和括号中的变量列表,以便将列表中的元素分配给左侧。例如:
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