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
- The compiler uses
StringBuilderfor 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
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.