vicjugador vicjugador - 4 months ago 20
Groovy Question

Inline Conditional Map Literal in Groovy

Working on some translation / mapping functionality using Maps/JsonBuilder in Groovy.

Is is possible (without creating extra code outside of the map literal creation) .. to conditionally include/exclude certain key/value pairs ? Some thing along the lines of the following ..

def someConditional = true

def mapResult =
[
"id":123,
"somethingElse":[],
if(someConditional){ return ["onlyIfConditionalTrue":true]}
]


Expected results:
If someConditional if false, only 2 key/value pairs will exist in mapResult.

If someConditional if true, all 3 key/value pairs will exist.

Note that I'm sure it could be done if I create methods / and split things up.. for to keep things concise I would want to keep things inside of the map creation.

Answer

You can help yourself with with:

[a:1, b:2].with{
    if (false) {
        c = 1
    }
    it
}

With a small helper:

Map newMap(m=[:], Closure c) {
    m.with c
    m
}

E.g.:

def m = newMap {
    a = 1
    b = 1
    if (true) {
        c = 1
    }
    if (false) {
        d = 1
    }
}

assert m.a == 1
assert m.b == 1
assert m.c == 1
assert !m.containsKey('d')

Or pass an inital map:

newMap(a:1, b:2) {
    if (true) {
        c = 1
    }
    if (false) {
        d = 1
    }
}
Comments