```// 1 regexBuilder.append( alts.split("|") ...
# codingconventions
e
Copy code
// 1
regexBuilder.append(
    alts.split("|")
        .map { it.trim() }
        .map { if (it.isEmpty()) "" else " $it"}
        .joinToString(prefix = "(?:", separator = "|", postfix = ")"))
or
Copy code
// 2
regexBuilder.append(
    alts.split("|")
        .map { it.trim() }.joinToString(
             prefix = "(?:",
             separator = "|",
             postfix = ")"
        ) { if (it.isEmpty()) "" else " $it" })
d
Copy code
alts.split("|")
        .map { it.trim() }
        .joinTo(regexBuilder, prefix = "(?:", separator = "|", postfix = ")") {
            if (it.isEmpty()) "" else " $it"
        }
Actually, even better: (Not equivalent!)
Copy code
alts.split("|")
        .map { it.trim() }
        .filter { it.isNotEmpty() }
        .joinTo(regexBuilder, prefix = "(?:", separator = "|", postfix = ")")
e
Thanks, @diesieben07! My favorite answer is “none of the above”.
d
haha, sorry. If only 1 or 2 are possible then definitely 2, but formatted differently, there should be a \n before joinToString
e
Empty elements are allowed. For example, “foo | bar | ” should become ” foo| bar|”
I wasn’t being sarcastic. I learn the most from “none of the above”, and it takes the most effort on the part of the writer, so thank you.
For a collection of
String
, are
joinTo
and
joinToString
equivalent?
d
Ah, so you are right, my 2nd solution is not equivalent
joinTo
works on
Appendable
, like
StringBuilder
😀 1
It avoids the intermediary
String
So
foo.append(thing.joinToString()
and
thing.joinTo(foo)
are the same
e
Thanks so much!
I’ve been changing other code of mine to use
joinTo
. My final code will be so elegant that it will go ballroom dancing. 💃 🕺
K 1
😂 1