Using the += operator on StringBuilder


#1

When I tried Java’s StringBuilder in Kotlin, I expected the following code to work:

fun main(args: Array<String>) {
    val sb = StringBuilder()
    sb += "hello"
    sb += 1
    sb += 'bit'
    println(sb)
}

As of Kotlin 1.2.20, the standard library does not predefine any operator function for StringBuilder.
To make the above code work, only a single extension method is needed:

operator fun StringBuilder.plusAssign(obj: Any?) {
    append(obj)
}

Is there a reason that this method is missing from the standard library, other than “too much other stuff to do”?


#2

I personally think, that it this overload is not necessary. StringBuilder is already a Builder and calls can be chained (which is not possible with += — or maybe it is, but is not a good idea for readability), which I think is enough. Just because operator overloading is possible, it doesn’t mean that everything should be an operator.


#3

We had considered adding plusAssign operator for StringBuilder here (KT-9031), but didn’t find the benefits of that compelling enough.