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
kotlin.String has a plus method:
a.plus(b)
See https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/plus.html for details.
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 HashMap, use this:
map.entries.joinToString(separator = ", ")
// Result:
// id=123, name=John, surname=Smith
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 + / 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
Or you can concatenate using the StringBuilder.
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
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.
There are various way to concatenate strings in kotlin Example -
a = "Hello" , b= "World"
Using + operator
a+b
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")
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.