Mad Map Mocking
Closures can have any number of arguments (optionally typed) and any number of statements.Closure addToY = { x -> x+y; }defines a closure
- A method with argument "x" , returning the sum of x and y.
- It's also an object.
- Like anonymous inner classes, but somehow easier.
- Lexically scoped:
yis defined outside the closure.
Map map = [ "x" : 7, "y" : "foo" ]
is equivalent to:Map map = new LinkedHashMap(2); map.put("x", 7); map.put("y", "foo");Map map = [ x : 7, y : "foo" ]means the same thing. (Parentheses are required if the key is not a string.)
groovy:000> Map m = [ f : { x -> x+1 } ]; m.f(3);
===> 4
HttpServletRequest r = [ getAttribute : { x -> "whatevaah" } ] as HttpServletRequest