noMAD
noMAD

Reputation: 7844

Not able to figure how this groovy closure works

I am new to groovy and was reading a testcase where I found the following:

def temp = {
        def temp = new HashMap()
        temp.clear()
        temp.set('A', '1')
        temp.set('B', '2')
        temp
    }

I wanted to know what value will the temp variable hold at the end of the definition since its used in a test case

assert Blah.blah(temp())

Upvotes: 0

Views: 53

Answers (1)

tim_yates
tim_yates

Reputation: 171144

It should be analogous to the map [ A:1, B:2 ].

Your assert line calls temp() which returns that map and then passes it to the Blah.blah method

You could rewrite the whole closure as:

def temp = { -> [ A:1, B:2 ] as HashMap }

And if a LinkedHashMap would do, you can even leave off the as HashMap bit

Upvotes: 2

Related Questions