130

A very basic question, what is the right way to concatenate a String in Kotlin?

In Java you would use the concat() method, e.g.

String a = "Hello ";
String b = a.concat("World"); // b = Hello World

The concat() function isn't available for Kotlin though. Should I use the + sign?

Daniele
  • 4,163
  • 7
  • 44
  • 95

15 Answers15

203

String Templates/Interpolation

In Kotlin, you can concatenate using String interpolation/templates:

val a = "Hello"
val b = "World"
val c = "$a $b"

The output will be: Hello World

Or you can concatenate using the StringBuilder explicitly.

val a = "Hello"
val b = "World"

val sb = StringBuilder()
sb.append(a).append(b)
val c = sb.toString()

print(c)

The output will be: HelloWorld

New String Object

Or you can concatenate using the + / plus() operator:

val a = "Hello"
val b = "World"
val c = a + b   // same as calling operator function a.plus(b)

print(c)

The output will be: HelloWorld

  • This will create a new String object.
AdamHurwitz
  • 9,758
  • 10
  • 72
  • 134
Avijit Karmakar
  • 8,890
  • 6
  • 44
  • 59
  • 9
    the operator "+" is translated into plus(), so you can either write `a.plus(b)` or `a + b` and the same bytecode is generated – D3xter May 25 '17 at 20:00
  • 26
    I looked into the bytecode and string interpolation uses StringBuilder internally – crgarridos Jan 30 '18 at 09:58
  • 1
    @crgarridos, Would this mean that for Kotlin using the string interpolation for concatenation `"Hello" + "Word"` is just as performant as using StringBuilder to append to a string, `someHelloStringBuilder.append("World")`? – AdamHurwitz Jun 19 '20 at 17:37
  • 2
    string interpolation refers to the resolution of variables inside of a literal string. so technically yes. – crgarridos Jun 19 '20 at 18:00
  • Both string interpolation and concatenation use StringBuilder internally. The only difference I noticed in the bytecode is that if there is only a single character between two variables then interpolation uses append(Char) instead of append(String) for this character. So I would say it is just syntactic sugar. It is important to use StringBuilder when multiple concatenations are done to a single variable, e. g. in a for loop. – Miloš Černilovský Dec 01 '21 at 10:42
  • I'm just starting to learn Kotlin so this might be a stupid question, but I thought val values couldn't be changed. So why am I allowed to write, val name = StringBuilder("Peter") name.append("Pan") would this not be altering the name variable? Thanks :) – james Dec 10 '21 at 05:59
28

kotlin.String has a plus method:

a.plus(b)

See https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/plus.html for details.

Harald Gliebe
  • 7,236
  • 3
  • 33
  • 38
  • 4
    The `+` operator is normal, not calling the translated operator function `plus` ... this is not idiomatic – Jayson Minard May 25 '17 at 22:18
  • why do you think so ? – incises Feb 28 '19 at 15:16
  • 5
    Don't forget to affect your result like I did, like `a = a.plus(b)` for instance – lorenzo Feb 18 '20 at 16:16
  • @lorenzo 's comment explains why this answer's less preferable to the solutions above. When concatenating is dependent on multiple if statements `plus()` is less practical than a `StringBuilder`'s append method ie. – Panos Gr Oct 16 '20 at 14:23
13

I agree with the accepted answer above but it is only good for known string values. For dynamic string values here is my suggestion.

// A list may come from an API JSON like
{
   "names": [
      "Person 1",
      "Person 2",
      "Person 3",
         ...
      "Person N"
   ]
}
var listOfNames = mutableListOf<String>() 

val stringOfNames = listOfNames.joinToString(", ") 
// ", " <- a separator for the strings, could be any string that you want

// Posible result
// Person 1, Person 2, Person 3, ..., Person N

This is useful for concatenating list of strings with separator.

Rhusfer
  • 571
  • 1
  • 9
  • 14
11

Try this, I think this is a natively way to concatenate strings in Kotlin:

val result = buildString{
    append("a")
    append("b")
}

println(result)

// you will see "ab" in console.
Ellen Spertus
  • 6,576
  • 9
  • 50
  • 101
Chinese Cat
  • 5,359
  • 2
  • 16
  • 17
10

Yes, you can concatenate using a + sign. Kotlin has string templates, so it's better to use them like:

var fn = "Hello"
var ln = "World"

"$fn $ln" for concatenation.

You can even use String.plus() method.

Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47
7

Similar to @Rhusfer answer I wrote this. In case you have a group of EditTexts and want to concatenate their values, you can write:

listOf(edit_1, edit_2, edit_3, edit_4).joinToString(separator = "") { it.text.toString() }

If you want to concatenate Map, use this:

map.entries.joinToString(separator = ", ")

To concatenate Bundle, use

bundle.keySet().joinToString(", ") { key -> "$key=${bundle[key]}" }

It sorts keys in alphabetical order.

Example:

val map: MutableMap<String, Any> = mutableMapOf("price" to 20.5)
map += "arrange" to 0
map += "title" to "Night cream"
println(map.entries.joinToString(separator = ", "))

// price=20.5, arrange=0, title=Night cream

val bundle = bundleOf("price" to 20.5)
bundle.putAll(bundleOf("arrange" to 0))
bundle.putAll(bundleOf("title" to "Night cream"))
val bundleString =
    bundle.keySet().joinToString(", ") { key -> "$key=${bundle[key]}" }
println(bundleString)

// arrange=0, price=20.5, title=Night cream
CoolMind
  • 26,736
  • 15
  • 188
  • 224
3

There are various way to concatenate strings in kotlin Example -

a = "Hello" , b= "World"
  1. Using + operator a+b

  2. Using plus() operator

    a.plus(b)

Note - + is internally converted to .plus() method only

In above 2 methods, a new string object is created as strings are immutable. if we want to modify the existing string, we can use StringBuilder

StringBuilder str = StringBuilder("Hello").append("World")
Daniele
  • 4,163
  • 7
  • 44
  • 95
3

The most simplest way so far which will add separator and exclude the empty/null strings from concatenation:

val finalString = listOf(a, b, c)
    .filterNot { it.isNullOrBlank() }
    .joinToString(separator = " ")
Yasir Ali
  • 1,785
  • 1
  • 16
  • 21
2

If you have an object and want to concatenate two values of an object like

data class Person(
val firstName: String,
val lastName: String
)

Then simply following won't work

val c = "$person.firstName $person.lastName"

Correct way in this case will be

"${person.firstName} ${person.lastName}"

If you want any string in between concatenated values, just write there without any helper symbol. For example if I want "Name is " and then a hyphen in between first and last name then

 "Name is ${person.firstName}-${person.lastName}"
Sourab Sharma
  • 2,940
  • 1
  • 25
  • 38
1

yourString += "newString"

This way you can concatenate a string

Kanagalingam
  • 2,096
  • 5
  • 23
  • 40
1

In Kotlin we can join string array using joinToString()

val tags=arrayOf("hi","bye")

val finalString=tags.joinToString (separator = ","){ "#$it" }

Result is :

#hi,#bye


if list coming from server

var tags = mutableListOf<Tags>() // list from server

val finalString=tags.joinToString (separator = "-"){ "#${it.tagname}" }

Result is :

#hi-#bye

Bhavin Patel
  • 872
  • 13
  • 30
1

I suggest if you have a limited and predefined set of values then the most efficient and readable approach is to use the String Template (It uses String Builder to perform concatination).

val a = "Hello"
val b = "World"
val c = "$a  ${b.toUpperCase()} !"

println(c) //prints: Hello  WORLD !

On the other hand if you have a collection of values then use joinToString method.

val res = (1..100).joinToString(",")
println(res) //prints: 1,2,3,...,100

I believe that some suggested solutions on this post are are not efficient. Like using plus or + or creating a collection for a limited set of entris and then applying joinToString on them.

Mr.Q
  • 4,316
  • 3
  • 43
  • 40
1

The best way of string concatenation is String Interpolation in Kotlin.

val a = "Hello"
val b = "World"

val mString = "$a $b"
val sString = "${a, b}, I am concatenating different string with."

//Output of mString : Hello World
//Output of sString : Hello World, I am concatenating different string with.
1

The idiomatically correct way to do string interpolation in Kotlin is as follows

val helloString = "Hello"
val worldString = "World"
val concatString = "$helloString $worldString"

Output

Hello World
Arunabh Das
  • 13,212
  • 21
  • 86
  • 109
0

Using Addition Assignment (+=) Operator:

Expression Equivalent Translates
a +=b a = a + b a.plusAssign(b)

Basic usage:

var message = "My message"
message += ", add message 2"

Will output: My message, add message 2


Generic functions, with optional spaces between words:

fun concat(vararg words: String, space: Boolean = false): String {
    var message = ""
    words.forEach { word -> message += word + if (space) " " else "" }
    return message
}

fun concat(vararg words: String, separator: String = ""): String {
    return string.joinToString(separator)
}

Calling generic function:

concat("one", "two", "three", "four", "five")
concat("one", "two", "three", "four", "five", space =  true)

Output:

onetwothreefourfive
one two three four five
ℛɑƒæĿᴿᴹᴿ
  • 4,983
  • 4
  • 38
  • 58