1. Introduction

In this short tutorial, we’ll investigate different ways of concatenating strings in Kotlin.

2. Using the plus() Method

Kotlin’s String class contains a plus() method:

operator fun plus(other: Any?): String (source)

It returns a String obtained by concatenating reference String with the String passed as an argument.

For example:

@Test
fun givenTwoStrings_concatenateWithPlusMethod_thenEquals() {
    val a = "Hello"
    val b = "Baeldung"
    val c = a.plus(" ").plus(b)

    assertEquals("Hello Baeldung", c)
}

Also, it is important to realize that if the object passed in isn’t a String, the String representation of the object will be used.

3. Using the + Operator

The simplest way of concatenating Strings in Kotlin is to use the + operator. As a result, we get a new String object composed of Strings on the left and the right side of the operator:

@Test
fun givenTwoStrings_concatenateWithPlusOperator_thenEquals() {
    val a = "Hello"
    val b = "Baeldung"
    val c = a + " " + b

    assertEquals("Hello Baeldung", c)
}

Another key point is that in Kotlin, thanks to operator overload, the + operator gets resolved to the plus() method.

In general, this is a common method for concatenating small numbers of Strings.

4. Using StringBuilder

As we know, String objects are immutable. With each concatenation using the + operator or plus() method, we get a new String object. In contrast, to avoid unnecessary String object creation, we can use a StringBuilder.

Hence, StringBuilder creates a single internal buffer that contains the final string.

Therefore, StringBuilder is more efficient when concatenating a large number of strings.

Here is a String concatenation example using StringBuilder:

@Test
fun givenTwoStrings_concatenateWithStringBuilder_thenEquals() {
    val builder = StringBuilder()
    builder.append("Hello")
           .append(" ")
           .append("Baeldung")

    assertEquals("Hello Baeldung", builder.toString())
}

Finally, we can use StringBuffer for thread-safe concatenation instead of StringBuilder.

5. Using String Templates

Kotlin also has a feature called String templates. String* templates contain expressions that get evaluated to build a *String.

String template expressions start with a dollar sign followed by the variable’s name.

Here is an example of String concatenation using templates:

@Test
fun givenTwoStrings_concatenateWithTemplates_thenEquals() {
    val a = "Hello"
    val b = "Baeldung"
    val c = "$a $b"

    assertEquals("Hello Baeldung", c)
}

The Kotlin compiler translates this code to:

new StringBuilder().append(a).append(" ").append(b).toString()

Finally, this process is String interpolation.

6. Append Strings Separated by Commas

In this section, we’ll learn how to append strings separated by commas.

6.1. Using the joinToString() Method

First, let’s start by defining a list of names in the fruitsList variable:

val fruitsList = listOf("apple", "banana", "orange")

Now, let’s use comma (,) as a separator within the joinToString() to concatenate these strings:

val fruitsCsv = fruitsList.joinToString(",")
assertEquals("apple,banana,orange", fruitsCsv)

Great! It looks like we’ve got the correct result.

Next, let’s say we wanted to transform these strings into an uppercase format while concatenating them. For this purpose, we can use the uppercase() method within a selector:

val fruitsUppercaseCsv = fruitsList.joinToString(","){it.uppercase()}
assertEquals("APPLE,BANANA,ORANGE", fruitsUppercaseCsv)

Lastly, we’ll explore another scenario where we want to *concatenate only those names that start with characters belonging to the [b, o] set*. So, let’s filter() using the startsWith() method and then concatenate those names with the joinToString() method:

val fruitsFilteredCsv = fruitsList.filter{it.startsWith("b") || it.startsWith("o")}
  .joinToString(",")
assertEquals("banana,orange", fruitsFilteredCsv)

With this, we’ve developed a good understanding of using the joinToString() method for concatenating the strings.

6.2. Using the reduce() Method

We can also use the reduce() method to combine the elements of the fruitsList list into a single string by repeatedly concatenating the accumulated string with each subsequent string:

val fruitsCsv = fruitsList.reduce { acc, str -> "$acc,$str" }
assertEquals("apple,banana,orange", fruitsCsv)

Perfect! This approach seems convenient and gives us the correct result.

6.3. Using the StringBuilder Class

Alternatively, we can use a StringBuilder object to concatenate the strings from the fruitsList list. Let’s implement this approach using a for loop:

val fruitsCsvBuilder = StringBuilder()

for ((index, str) in fruitsList.withIndex()) {
    fruitsCsvBuilder.append(str)
    if (index < fruitsList.size - 1) {
        fruitsCsvBuilder.append(",")
    }
}

val fruitsCsv = fruitsCsvBuilder.toString()

We must note that we append a comma after each string except the last one.

Further, let’s verify the contents of the fruitsCsv variable that holds our result:

assertEquals("apple,banana,orange", fruitsCsv)

Fantastic! It looks like we’ve nailed this.

7. Conclusion

In this article, we’ve learned a few ways to concatenate String objects in Kotlin. Furthermore, we explored multiple ways to append strings separated by commas.

As always, all code presented in this tutorial can be found over on GitHub.