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?
Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.
As we know, String objects are immutable. With each concatenation using the + operator or plus() method, we get a new String object.
To concatenate strings in Kotlin, you can use concatenation operator + .
In C, the strcat() function is used to concatenate two strings. It concatenates one string (the source) to the end of another string (the destination).
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
StringBuilder
for String templates which is the most efficient approach in terms of memory because +
/plus()
creates new String objects.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
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
kotlin.String
has a plus
method:
a.plus(b)
See https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/plus.html for details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With