118

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
  • 3,874
  • 7
  • 37
  • 93

12 Answers12

187

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.
Adam Hurwitz
  • 8,325
  • 6
  • 64
  • 117
Avijit Karmakar
  • 7,928
  • 6
  • 38
  • 57
  • 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
  • 25
    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")`? – Adam Hurwitz 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
  • 6,817
  • 2
  • 30
  • 37
  • 3
    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
  • 3
    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
  • 561
  • 1
  • 9
  • 14
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
  • 13,804
  • 1
  • 24
  • 44
6

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
  • 22,602
  • 12
  • 167
  • 196
6

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,328
  • 9
  • 51
  • 90
Chinese Cat
  • 5,108
  • 2
  • 14
  • 15
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
  • 3,874
  • 7
  • 37
  • 93
1

yourString += "newString"

This way you can concatenate a string

Kanagalingam
  • 1,926
  • 5
  • 19
  • 38
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
  • 3,929
  • 3
  • 39
  • 38
1

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
  • 7,280
  • 2
  • 26
  • 35
1

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,735
  • 1
  • 16
  • 21
0

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
  • 732
  • 12
  • 29