Introduction :
String is immutable in Kotlin. If we concatenate two or more strings, it will generate one new string. We have different different ways to concatenate in Kotlin. In this tutorial, I will show you how to solve it with examples.
String plus method :
String plus method is defined as below :
public operator fun plus(other: Any?): String
It takes one string as the argument and returns the final result string i.e. concatenate the reference string with the argument string. The argument is of type Any. If we don’t pass a string, it will use the string representation of that object.
Example :
fun main() {
val givenStr = "Hello"
println(givenStr.plus(" World !!"))
}
Output :
Hello World !!.
The result is a string. We can keep using plus as a chain :
fun main() {
val givenStr = "Hello"
println(givenStr.plus(" World").plus(" !!"))
}
+ mathematical operator :
+ operator joins the string to its left and right side. This operator is actually simplifies to the above plus() method. We can concatenate infinite number of strings using this :
fun main() {
val givenStr = "Hello"
println(givenStr + " World" + " !!")
}
String template :
String templates are used to generate a string from strings and template expressions. Template expressions are evaluated and concatenate into a string. Template expressions starts with a dollar sign. For example :
fun main() {
val givenStr = "Hello"
val secondStr = "World !!"
println("$givenStr $secondStr")
}
It will print :
Hello World !!.
StringBuilder :
StringBuilder joins multiple strings using a buffer and gives the final string. But the other methods like plus generates one new string on each call. If we join hundreds of strings using plus, all intermediate strings will be useless. These will take unnecessary memory and the garbage collector will have to clean them periodically.
But, with StringBuilder, no intermediate strings are generated. So, it is more efficient for large number of strings.
The below example uses StringBuilder to join multiple strings :
fun main() {
val firstStr = "Hello"
val secondStr = "World"
val thirdStr = "!!"
val strBuilder = StringBuilder()
val finalStr = strBuilder.append(firstStr).append(" ").append(secondStr).append(" ").append(thirdStr).toString()
print(finalStr)
}
Output :
Hello World !!.