无法理解这个groovy闭包是如何工作的

无法理解这个groovy闭包是如何工作的,groovy,Groovy,我是groovy新手,在阅读一个测试用例时发现了以下内容: def temp = { def temp = new HashMap() temp.clear() temp.set('A', '1') temp.set('B', '2') temp } 我想知道temp变量在定义结束时将保持什么值,因为它在测试用例中使用 assert Blah.blah(temp()) 它应该类似于地图[A:1,B:2]

我是groovy新手,在阅读一个测试用例时发现了以下内容:

def temp = {
        def temp = new HashMap()
        temp.clear()
        temp.set('A', '1')
        temp.set('B', '2')
        temp
    }
我想知道temp变量在定义结束时将保持什么值,因为它在测试用例中使用

assert Blah.blah(temp())

它应该类似于地图
[A:1,B:2]

断言行调用
temp()
,它返回该映射,然后将其传递给
Blah.Blah
方法

您可以将整个闭包重写为:

def temp = { -> [ A:1, B:2 ] as HashMap }
如果LinkedHashMap可以,您甚至可以将
作为HashMap