https://kotlinlang.org logo
Title
c

Colton Idle

02/19/2021, 5:35 PM
Just wanted to see if anyone knows of an idiomatic way of adding a
,
between strings in a string builder. I know
joinToString
exists and it works great for arrays, but I basically want the same functionality for a string builder. Here's what I'm currently doing (no commas yet):
topic.data.forEach {
                    myBuilder.append("${it.city} ${it.status}")
                }
            }
Maybe I'm missing something basic. Thanks
v

Vampire

02/19/2021, 5:40 PM
Is using a
StringBuilder
a fixed necessity? If not you could for example do
topic.data.joinToString(',') { "${it.city} ${it.status}" }
n

nanodeath

02/19/2021, 5:44 PM
v

Vampire

02/19/2021, 5:48 PM
Ah, yes, you are right,
StringBuilder
is
Appendable
. So then it would be
topic.data.joinTo(myBuilder, ",") { "${it.city} ${it.status}" }
.
1
c

Colton Idle

02/19/2021, 5:49 PM
@nanodeath Hm. But I would need to make an empty array first and then call myEmptyArray.joinTo(myStringBuilder, ...).
Oh. I could use the topic.data directly. 🤦
👆 2
😁 1
n

nanodeath

02/19/2021, 5:50 PM
I don't love that the city + status string generation is itself likely using a string builder, but I don't think there's much you can do about that without like...building up an arraylist by hand, and that's just not worth it.
c

Colton Idle

02/19/2021, 5:50 PM
@Vampire string builder isn't a fixed necessity. I guess I can just use your join to string suggesstion to. It's just muscle memory to use string builder when building strings. 😄 I'm sure it's a micro optimization now, but I wonder if there's any difference.
n

nanodeath

02/19/2021, 5:51 PM
readability wise, probably
c

Colton Idle

02/19/2021, 5:51 PM
Anyone have any preference/idiomatic thoughts on topic.data.joinToString(',') { "${it.city} ${it.status}" } vs topic.data.joinTo(myBuilder, ",") { "${it.city} ${it.status}" }
v

Vampire

02/19/2021, 5:51 PM
Bad muscle memory then, should have
StringJoiner
in it 😄
first one imho
n

nanodeath

02/19/2021, 5:51 PM
I'd use
joinToString
if you don't already have and need a builder
c

Colton Idle

02/19/2021, 5:58 PM
Thanks everyone. Appreciate your time and experience.
👍 1