有没有一种方法可以使用map中前一个键分配的值,例如:
def x = [
a: someList.sum(),
b: anotherList.sum(),
c: someList.sum() / anotherList.sum()
]
我希望 'c' 的值为 a/b,是否有一种快捷方式,而不需要在计算 'c' 时重新计算总和。
有没有一种方法可以使用map中前一个键分配的值,例如:
def x = [
a: someList.sum(),
b: anotherList.sum(),
c: someList.sum() / anotherList.sum()
]
def x = [
a: 8,
b: 2,
c: a / b
]
当计算键 c
的值时,Groovy会尝试访问名为 a
的变量或属性,但由于变量/属性不存在而失败。但是,您可以利用该属性查找并执行以下操作:
def x = [:].with {
a = 8
b = 2
c = a / b
delegate
}
Map
开始。然后使用with(Closure)
来执行putAt()
和get()
命令对Map
进行操作。上面的示例相当于...def x = [:].with {
putAt('a', 8)
putAt('b', 2)
putAt('c', get('a') / get('b'))
delegate
}
Map
本身以使其分配给 x
。it
而不是 delegate
。 - Will
定义 a = 1;定义 x = [a: a, b: a + 1]
。 - JB Nizetdef x = [a: 1]; x.b = x.a + 1
。 - dmahapatro