Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 7

[ 141 ]

def namedParamsMethod1(Map params) {
assert params.a == 1
assert params.b == 2
assert params.c == 3
true
}

expect: "We can pass named parameters in any order"
namedParamsMethod1(a:1, b:2, c:3)
namedParamsMethod1(b:2, c:3, a:1)
namedParamsMethod1(c:3, a:1, b:2)

If the method has other parameters, Groovy allows the map entries to be placed
before or after the other parameters. The map entries will still get collected and
passed as the first argument:


def namedParamsMethod2(Map params, String param2, String param3) {
assert params.a == 1
assert params.b == 2
assert params.c == 3
assert param2 == "param2"
assert param3 == "param3"
true
}

expect: "We can mix named and regular parameter in any order"
namedParamsMethod2(a:1, b:2, c:3, "param2", "param3")
namedParamsMethod2("param2", b:2, "param3", c:3, a:1)
namedParamsMethod2(c:3, "param2", a:1, "param3", b:2)

In fact, the map entries can be interspersed among the other parameters in any order
we like. Groovy will collect the map entries and pass them as the first parameter.
It will then scan the rest of the parameters from left to right and assign them to the
subsequent parameters of the method. We can also drop the method call parentheses,
which allows us to invoke the method call as follows:


expect: "We can leave out parentheses"
namedParamsMethod2 a:1, b:2, c:3, "param2", "param3"
namedParamsMethod2 "param2", b:2, "param3", c:3, a:1
namedParamsMethod2 c:3, "param2", a:1, "param3", b:2
Free download pdf