Michal Kordas
Michal Kordas

Reputation: 10925

Groovy way to conditionally append to a String

Good old java way to conditionally append something to string is as follows:

if (booleanFlag) {
    myString += "something to append"
}

Can I do the same in more groovy way, ideally in one line?

Upvotes: 12

Views: 23511

Answers (6)

smac89
smac89

Reputation: 43078

Here is a groovy way using GString closures:

>>> def world = false
>>> def people = true
>>>
>>> def message = "Hello${sw -> if (world) sw << ' World'; if (people) sw << ' People'}"
>>>
>>> message
Hello People
>>>
>>> people = false
>>> world = true
>>>
>>> message
Hello World
>>>
>>> world = false
>>> message
Hello

The string looks kinda long and could do with some indentation, but groovy shell did not allow me to split the lines. Switched to an IDE, turns out you can write the string better like this (with the help of triple quote strings):

def message = 
"""Hello${sw -> 
    if (false) sw << ' World!'
    if (false) sw << ' People!'
    if (true)  sw << ' Groovy!'
}"""

Now that's groovy!

Upvotes: 7

Will
Will

Reputation: 14519

Here's a solution creating a String.metaClass.when method:

String.metaClass.when = { it ? delegate : '' }

Testing:

flag = true
myString = 'foo '
myString += "to append".when flag
assert myString == 'foo to append'

myString = 'foo ' + "to append".when(false)
assert myString == 'foo ' 

Upvotes: 2

Emmanuel Rosa
Emmanuel Rosa

Reputation: 9885

I think this pattern is a good candidate for some meta-programming.

def myString = 'Hello'

use(StringBuilderCategory) {
    assert new StringBuilder(myString).append(true, 'World').toString() == 'HelloWorld'
    assert new StringBuilder(myString).append(false, 'World').toString() == 'Hello'
}

class StringBuilderCategory {
    static StringBuilder append(StringBuilder builder, boolean condition, String str) {
        if(condition) {
            builder.append(str)
        } else {
            builder
        }
    }
}

I used a StringBuilder to avoid implying that Strings are mutable, but a similar method can be added to String to get it down to this:

use(TheCategory) {
    myString = myString.append(booleanFlag, 'something to append')
}

Of course there's the option of using the meta class instead of a category.

Upvotes: 1

Mark Ludwinski
Mark Ludwinski

Reputation: 1

Looks like one line to me:

if (booleanFlag) myString += "something to append"; 

Upvotes: -1

cjstehno
cjstehno

Reputation: 13984

A very Groovy way to do this would be with GStrings:

"$myString${booleanFlag ? 'something to append' : ''}"

Upvotes: 19

Opal
Opal

Reputation: 84756

Try:

def b = true
def s = 's'

s += b ? 's' : ''

Upvotes: 6

Related Questions