Reputation: 10925
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
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
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
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 String
s 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
Reputation: 1
Looks like one line to me:
if (booleanFlag) myString += "something to append";
Upvotes: -1
Reputation: 13984
A very Groovy way to do this would be with GStrings:
"$myString${booleanFlag ? 'something to append' : ''}"
Upvotes: 19