Mad Map Mocking

Four pieces to this

  1. Closures
    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: y is defined outside the closure.
    Closures can have any number of arguments (optionally typed) and any number of statements.
  2. Maps (syntactic sugar)
    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.)
  3. Maps members can be accessed like properties or methods
    (from the interactive program "groovysh")
    groovy:000> Map m = [ f : { x -> x+1 } ]; m.f(3);
    ===> 4
    
  4. Lying to the type system.
    HttpServletRequest r = [ getAttribute : { x -> "whatevaah" } ] as HttpServletRequest
    

Prev Next