Junior — Middle
What methods can be used to concatenate strings in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, strings can be concatenated in several ways:
- Using the
+operator:
val result = "Hello, " + "world!"
- String interpolation (string templates):
val name = "John"
val greeting = "Hello, $name!"
- Using the
plus()method:
val result = "Hello, ".plus("world!")
- Using
StringBuilderfor efficient concatenation of many strings:
val builder = StringBuilder()
builder.append("Hello, ")
builder.append("world!")
val result = builder.toString()
- Using the
joinToString()function to concatenate collections of strings:
val words = listOf("Hello", "world")
val result = words.joinToString(separator = ", ")
The choice of method depends on the task and performance considerations.