https://kotlinlang.org logo
Title
a

Arun

03/01/2018, 2:36 PM
Is there a good example on how to use
buildString()
? https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/build-string.html
d

diesieben07

03/01/2018, 2:38 PM
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

Arun

03/01/2018, 2:44 PM
Thanks!
d

deviant

03/01/2018, 2:53 PM
i wish it would done like this:
buildString {
    +"Hello "
    +name
    +"!"
}
d

diesieben07

03/01/2018, 3:06 PM
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:
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

Ruckus

03/01/2018, 3:09 PM
Sorry, I was thinking backward 😁
🙃 1
Maybe someday if we get syntax for multiple receivers