Is there a better way of writing this: ``` over...
# codereview
e
Is there a better way of writing this:
Copy code
override fun toString() =
        StringBuilder("MatchResult(\"").apply {
            append(baseString())
            append("\"")
            append(slotString())
            append(if (parameters.isEmpty()) "" else ", parameters: $parameters")
            append(if (skippedWords == 0) "" else ", skippedWords: $skippedWords")
            append(if (aliasedWords == 0) "" else ", aliasedWords: $aliasedWords")
            append(intentName?.let { ", intentName: $it" } ?: "")
            append(", capturedWords: $capturedWords)")
        }.toString()
It looks godawful as one big string interpolation.
a
append(if (aliasedWords == 0) "" else ", aliasedWords: $aliasedWords")
— those look odd, because appending “” is a no-op
I think if you pulled those ‘if’s and (and converted the ‘?.let’ to an ‘if’ too) it would look more sane
💯 1
also, use the
buildString
stdlib function to supply the StringBuilder creation and toString()
but in priciple, building up a string using a builder block on a StringBuilder is pretty normal, imho
m
Just in case you're not sure what was meant by 'pull thos e 'ifs'',
if(parameters.isNotEmpty) append(", parameters: $parameters)
👍 1
e
Thanks, everyone. Yeah those if append empty strings were pretty stupid. They were left over from when I put the values in local variables.
e
My attempt at readability. Not tested.
m
I think this is better. Using StringBuilder rather than an Array and then 2 StringBuilders (String Templating and the joinToString). Also note that there is a isNotEmpty function available on things that have isEmpty
@Ellen Spertus I missed something the last time I looked at this. You can see in my example that I append the description string and then append the object rather than using String Templating of Kotlin. I'm not sure how 'smart' the compiler is, or if it always uses a StringBuilder when there's templating. If it always uses StringBuilder, then your example will be creating a lot of them. And for above, one could add an operator override for
plus
that is effectively an
append
, but I'm not convinced it would help, rather than harm, the readability of the code.
1