Passing Maps in Groovy (or "Groovy did what?!")

  class Robot 
  { 
    def type 
    def height 
    def width 

    def access(location, weight, fragile) 
    { 
      print "Received fragile? ${fragile}, weight: ${weight}, loc: ${location}" 
    } 
  } 

  robot = new Robot(type: 'arm', width: 10, height: 40) 
  println "${robot.type}, ${robot.height}, ${robot.width}" 
  robot.access(50, x: 30, y: 20, z: 10, true)

Republished from Venkat Subramaniam’s Programming Groovy (Beta, p. 39)

…outputs the following:

  arm, 40, 10
  Received loc: ["x":30, "y":20, "z":10], weight: 50, fragile? true

If you’re a Ruby programmer, the second line is going to look seriously bizarre. If you’re not, I’ll explain why. In Ruby, you can pass a Hash (think java.util.Map) inline in a method call with the following syntax:

  foo("param1", param2, :hash_key1 => val1, :hash_key2 => val2)

According to Groovy, when a Map is inlined as a argument to a function, by convention, it is the first parameter on the method. If it is not passed in as the first argument then it is coerced into becoming the first argument. The Ruby interpreter will error if you pass an inlined Hash as any argument other than the last. Forgive me but Groovy’s coercion of parameter ordering is just fucking weird.

Posted by evan on Tuesday, March 04, 2008

blog comments powered by Disqus