139

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?

15 Answers 15

212

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.
Sign up to request clarification or add additional context in comments.

6 Comments

the operator "+" is translated into plus(), so you can either write a.plus(b) or a + b and the same bytecode is generated
I looked into the bytecode and string interpolation uses StringBuilder internally
@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")?
string interpolation refers to the resolution of variables inside of a literal string. so technically yes.
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.
|
31

kotlin.String has a plus method:

a.plus(b) 

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

4 Comments

The + operator is normal, not calling the translated operator function plus ... this is not idiomatic
why do you think so ?
Don't forget to affect your result like I did, like a = a.plus(b) for instance
@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.
14

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. 

2 Comments

it is buildString { instead of stringBuild {
@arnonuem I've fixed it (as you should have felt free to do).
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.

Comments

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.

2 Comments

The + operator is normal, not calling the translated operator function plus ... this is not idiomatic
Could you please explain why you think the plus version of + is not idiomatic ?
8

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 

Comments

4

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 = " ") 

Comments

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") 

Comments

3

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}" 

Comments

3

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. 

Comments

3

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 

Comments

1

yourString += "newString"

This way you can concatenate a string

Comments

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

Comments

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.

Comments

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.