It's possible to use Map.withDefault(Closure)
Groovy Enhancement method or the Spread operator (*
), besides using the plus (+
) and left shift (<<
) operators:
Map.withDefault(Closure init)
def defaults = [ a: true, b: false, ]
def args = [ a: false, ]
def options = args.withDefault { defaults[it] }
assert options == [ a: false ]
assert [ options["a"], options["b"] ] == [ false, false ]
assert options == [ a: false, b: false ]
Map.withDefault
wraps a map using the decorator pattern with a wrapper that intercepts
all calls to get(key)
. If an unknown key is found, a default value
will be stored into the Map before being returned. The default value
stored will be the result of calling the supplied Closure with the key
as the parameter to the Closure.
If you have a requirement that every boolean in the Map has the same value by default, then you could write the following:
def args = [ a: true, ]
def options = args.withDefault { false }
assert options == [ a: true ]
assert [ options["a"], options["b"], options["c"] ] == [ true, false, false ]
assert options == [ a: true, b: false, c: false ]
Spread Operator (*
)
def defaults = [ a: true, b: false, ]
def args = [ a: false, ]
assert [ foo: "bar", *: defaults, *: args, ] == [ a: false, b: false, foo: "bar" ]
Roughly similar to the plus operator but works only on map literals.
Plus Operator (+
)
assert [ a: true, b: false ] + [ a: false ] == [ a: false, b: false ]
Roughly equivalent to Map m = new HashMap(); m.putAll(left); m.putAll(right); return m;
.
Left Shift Operator (<<
)
assert [ a: true, b: false ] << [ a: false ] == [ a: false, b: false ]
Roughly equivalent to left.putAll(right); return left;
.
Also, you could get the default value by demand in a wrapper function similar to what Map.withDefault
does:
Map.get(Object key, Object defaultValue)
def defaults = [ a: true, b: false, ]
def args = [ a: false, ]
assert args.get("a", defaults["a"]) == false
assert args.get("b", defaults["b"]) == false
For a method which doesn't mutate the map, consider instead using Map#getOrDefault(Object, Object) or consider using Groovy's MapWithDefault.
- Plus and Shift operator sections were inspired by Tim Yates' answer.
- Checkout Groovy's Enhancement Map documentation for better understanding.