Is there a good example on how to use `buildString...
# announcements
a
Is there a good example on how to use
buildString()
? https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/build-string.html
d
Copy code
buildString {
    append("Hello ")
    append(name)
    append('!')
}
Bit of a contrived example, since here string templates would be a cleaner solution. But it get's the idea across I think.
a
Thanks!
d
i wish it would done like this:
Copy code
buildString {
    +"Hello "
    +name
    +"!"
}
d
That would require an additional wrapper object around the
StringBuilder
to add the necessary
String
extension function. If you are willing to pay that cost you can do something like this:
Copy code
inline fun myBuildString(builder: StringBuilderContext.() -> Unit): String {
    return StringBuilderContext(StringBuilder()).apply(builder).toString()
}

class StringBuilderContext(private val builder: StringBuilder) {
    operator fun String.unaryPlus() {
        builder.append(this)
    }
    override fun toString() = builder.toString()
}
But I don't think it should be the default.
r
Sorry, I was thinking backward 😁
🙃 1
Maybe someday if we get syntax for multiple receivers