The Java API has <https://docs.oracle.com/en/java/...
# stdlib
k
The Java API has a constructor that allows you to pass an initial String or CharSequence to initialize it with a sensible initial capacity, e.g.:
Copy code
val str = StringBuilder("The value of your purchase is ").apply {
    ...do things...
    append(things)
}.toString()
This would be neater if
buildString
had an overload that takes a
String
or
CharSequence
parameter. Without it, we would have to do the above, or the even worse:
Copy code
val str = buildString("The value of your purchase is ".length + 16) {
    append("The value of your purchase is ")
    ...do things...
    append(things)
}
Has anyone ever made a request for such a function and what was the outcome?
My use case was that I was trying to refactor this:
Copy code
var str = "Some long string"
if (condition1) str += "another string"
if (condition2) str += "and another"
To make
str
into an immutable
val
using something like this (if only
buildString(string, block)
existed):
Copy code
val str = buildString("Some long string") {
    if (condition1) append("another string")
    if (condition2) append("and another")
}
j
Even if this overload existed, I would prefer for readability to put the first append inside the block like all the others. I don't feel like it should have a special status compared to any non-first unconditional
append
.