Concatenate Strings in Groovy

1. Introduction

Groovy has two ways of instantiating strings. One is plain java.lang.String and second are groovy.lang.GString.
Plain string is represented with a single or double quote. However, the single quote doesn't support interpolation. Interpolation is supported only with a double quote and when it is present, then it becomes GString. In this article, we will see these different types of string representations in Groovy and how to concatenate them.


2. Types of Strings

So, there are 4 main types of string representations which are instantiated either through java.lang.String or groovy.lang.GString in Groovy - single-quoted string, double-quoted string, GString, and triple single-quoted string. Let's talk about them with some examples:
Let's first see the single-quoted string. It is also known as a plain string:

'My name is Joe Smith'

Here is an example for double-quoted string:

"My name is Joe Smith"

Double-quoted string also does support interpolation. When we add interpolation in it, it becomes GString. An interpolation is an act of replacing a placeholder in the string with its value upon evaluation of the string. The placeholder expressions are surrounded by ${}:


"My name is $name"

Now, we will see the example of a triple single-quoted string. It is used for multiline string, but it doesn’t support interpolation:

'''
My name is
Joe
Smith
'''
Now, let's see how to do concatenation of these different types of strings.

3. Using + Operator

Let's start with the simple '+' operator to see how we can concatenate two plain strings:

'My name is ' + first + ' ' + last

Note, here first and last are variables.
Let's write a simple test which sets the value of first and last variable and verify the return string is as expected:

name.first = 'Joe';
name.last = 'Smith';
def expected = 'My name is Joe Smith'
assertToString('My name is ' + first + ' ' + last, expected)

Similarly, we can use the double-quote instead of single-quote for concatenating the two plain strings.

4. Using GString

Let's now do the concatenation with GString:

"My name is $first $last"

The output of this string will be:

My name is Joe Smith

Note, here we have used the double-quote instead of single-quote. If we use single-quote, it will consider $first and $last as literals and output will be:

My name is $first $last

5. Using GString Closure

A closure in Groovy is an open, anonymous, block of code that can take arguments, return a value and be assigned to a variable.
In GString, when the placeholder contains an arrow, ${→}, the expression is actually a closure expression. Let's see the below example:

"My name is ${-> first} ${-> last}"

Let's do a simple test to understand the difference between GString and GString closure:

def first = "Joe";
def last = "Smith";
def eagerGString = "My name is $first $last"
def lazyGString = "My name is ${-> first} ${-> last}"

assert eagerGString == "My name is Joe Smith"
assert lazyGString == "My name is Joe Smith"

first = "David";

assert eagerGString == "My name is Joe Smith"
assert lazyGString == "My name is David Smith"

Here, eagerGString represents plain interpolation of GString and lazyGString represents interpolation with closure expression.
We also do notice here that in plain interpolation, the value is actually bound at the time of creation of the GString. That's why there is no change in eagerGString value even after changing the first variable value.
However, with a closure expression, the closure is called upon each coercion of the GString into String, resulting in an updated lazyGString containing the new value of the first variable.

6. Using String Concat Method

Now, let's see how to use String class concat() method to do the concatenation:

'My name is '.concat(first).concat(' ').concat(last)

7. Using LeftShift << Operator

Next, let's see the usage of the left shift '<<' operator to concatenate the strings:

'My name is ' << first << ' ' << last

String class also does have leftShift() method which overrides the << operator to provide an easy way of appending strings.

8. Using Array Join Method

We will now use an Array to concatenate the objects. An Array has a method called join() which concatenates the toString() representation of each item in the array, with the given String as a separator between each item.

['My name is', first, last].join(' ')

Note, here the separator is empty space.

9. Using Array Inject Method

Next, let's see how to use an inject(Object initialValue, Closure closure) method of Array to do the concatenation. This method iterates through the given Object, passing in the initial value to the closure along with the first item:

[first,' ', last]
  .inject(new StringBuffer('My name is '), { initial, name -> initial.append(name); return initial }).toString()

So, here it iterates through the array having [first, ' ', last]. It will pass the initial value as 'My name is ' and then keep appending each element of the array 'Joe' (value of first), ' ', 'Smith' (value of last).

10. Using StringBuilder

Now, let's use StringBuilder append() method for concatenating the String objects:

new StringBuilder().append('My name is ').append(first).append(' ').append(last)

11. Using StringBuffer

Next, let's see how to use StringBuffer append() method to do the concatenation:

new StringBuffer().append('My name is ').append(first).append(' ').append(last)

12. Concatenate Multiline String

Now, let's see how to do concatenation for triple single-quoted ('''  ''') strings:

name.first = '''
Joe
Smith
''';
name.last = 'Junior'

We can use any of the methods discussed in this article to concatenate this triple single-quoted string with other String objects. Let us take one example of how to do it using String concat() method:

'My name is '.concat(first).concat(' ').concat(last)

The output of the String will be:

'''My name is 
Joe
Smith
 Junior''';

Note, that there is an empty space before 'Junior'. concat(' ') method has added this. However, String does have stripIndent() method to remove such indentation.

13. Conclusion

To summarize, in this article we have seen various ways of doing the String concatenation in Groovy.

The full implementation of this tutorial can be found over on GitHub.

No comments:

Post a Comment

Most Viewed Posts