Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy way to conditionally append to a String

Tags:

append

groovy

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?

like image 306
Michal Kordas Avatar asked Dec 17 '15 13:12

Michal Kordas


People also ask

How do I append in Groovy?

Groovy - add() Append the new value to the end of this List. This method has 2 different variants. boolean add(Object value) − Append the new value to the end of this List.

How do I join strings in Groovy?

The concatenation of strings can be done by the simple '+' operator. Parameters − The parameters will be 2 strings as the left and right operand for the + operator.

What does == mean in Groovy?

Behaviour of == In Java == means equality of primitive types or identity for objects. In Groovy == translates to a. compareTo(b)==0, if they are Comparable, and a. equals(b) otherwise.

What does [:] mean in Groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]


1 Answers

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

"$myString${booleanFlag ? 'something to append' : ''}"
like image 76
cjstehno Avatar answered Oct 09 '22 01:10

cjstehno