Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way of using StringBuilder in kotlin? [closed]

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) ??

like image 969
curioushikhov Avatar asked Aug 20 '19 13:08

curioushikhov


People also ask

What is the best for using StringBuilder instead?

What is the best reason for using StringBuilder instead of String? A. StringBuilder adds support for multiple threads.

What is the advantage of using StringBuilder?

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.

How do I append string to string in Kotlin?

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.

How do I remove the last character from a string in Kotlin?

To remove last N characters from a String in Kotlin, use String. dropLast() method.

How does a StringBuilder work?

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.

Does StringBuilder create new string?

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.


1 Answers

@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) } 
like image 54
curioushikhov Avatar answered Sep 22 '22 23:09

curioushikhov