Search code examples
stringkotlinidioms

Idiomatic way of using StringBuilder in kotlin?


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


Solution

  • @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) }