Question

Consider following Groovy Script:

class Scaffold{
 def methodMissing(String name, args) {
    println name
    println args[0]
    println args[1]
 }
}

new Scaffold().field('VendorId', 'entity': 'Vendor', 'value': '1');

When I run it, the output is:

field
[entity:Vendor, value:1]
VendorId

I was expecting args[0] t be 'VendorId' and args[1] to be the map.

Any ideas why the order seems to be reversed? Will this behavior be consistent?

Was it helpful?

Solution

That is correct. In Groovy, all map entries in a method call will be collected and passed in as the first parameter. In a methodMissing, they are passed as the first element in the arguments array:

def methodMissing(String name, args) {
  "$name ${args[0]} ${args[1]}"
}

assert foo(a: 1, 'john doe', b: 2) == "foo [a:1, b:2] john doe"

For a non-missing method call:

def method(map, name) { "$map $name" }
assert method(a: 1, 'test', b: 2) == "[a:1, b:2] test"

You can force the map normal order if you declare it using square brackets:

def methodMissing(String method, args) {
  "$method ${args[0]} ${args[1]}"
}

assert echo("foo", [a: 1, b: 2]) == "echo foo [a:1, b:2]"

http://mrhaki.blogspot.com.br/2009/09/groovy-goodness-named-parameters-are.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top