I often write pretty complex toString() methods and this question is always bothering me - which variant is more clear to read. Following examples are simplified, usually there are a lot of conditionals, so single liners are not fit.
1) like in plain java:
val sb = StringBuilder()
sb.append(data)
val string = sb.toString()
2) apply + toString() - not pretty yeah?
val string = StringBuilder().apply {
append(data)
}.toString()
3) run + toString() last statement also is not superb
val string = StringBuilder().run {
append(data)
toString()
}
4) ??
What is the best reason for using StringBuilder instead of String? A. StringBuilder adds support for multiple threads.
StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.
There are different ways to concatenate strings in Kotlin. For example, we can use the $ operator or we can use the append() function or we can simply use the "+" operator to join two strings.
To remove last N characters from a String in Kotlin, use String. dropLast() method.
The StringBuilder works by maintaining a buffer of characters (Char) that will form the final string. Characters can be appended, removed and manipulated via the StringBuilder, with the modifications being reflected by updating the character buffer accordingly. An array is used for this character buffer.
StringBuilder will only create a new string when toString() is called on it. Until then, it keeps an char[] array of all the elements added to it. Any operation you perform, like insert or reverse is performed on that array.
@dyukha answer is 100% best choice: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/build-string.html
It's just
val s = buildString { append(data) }
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