Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Power Groovy DSL Features


[ 140 ]

Named parameters


We have touched upon the concept of named parameters already. In a previous
chapter, we looked at how Groovy allows us to construct a POGO by using a
default built-in constructor that accepts a Map argument. We can construct a
POGO by passing an inline Map object to the constructor. Groovy uses the map
object to initialize each property of the POGO in turn. The map is iterated and the
corresponding setter is invoked for each map element that is encountered:


class POGO {
def a = 0
def b = 0
def c = 0
}

given:
def pogo1 = new POGO(a:1, b:2, c:3)
def pogo2 = new POGO( b:2, c:3)
def pogo3 = new POGO(b:2, a:3)
expect:
pogo1.a == 1
pogo1.b == 2
pogo1.c == 3
and:
pogo2.a == 0
pogo2.b == 2
pogo2.c == 3
and:
pogo3.a == 3
pogo3.b == 2

When we pass a Map object to a constructor, the parentheses [] can be left out. We
can also list the property values in any order we like. If a property is excluded, the
corresponding setter will not be called, so its default value will be preserved.


Groovy also allows the same parameter-passing scheme to be used with method
calls. If we invoke a method and pass a list of map elements in the same fashion, as
shown in the preceding code, Groovy will collect the map elements into a Map object
and pass this to the method as the first parameter. Parameters passed in this way
are generally known as named parameters. The key that we use for each parameter
provides a name for the parameter, which otherwise is anonymous.


http://www.ebook3000.com
Free download pdf