Hello, I am using `joinToString(", ")` to construc...
# announcements
m
Hello, I am using
joinToString(", ")
to construct a comma separated string from a list of names. What would be an idiomatic way to make the last comma an "and" instead? I am getting "a, b, c, d", but want to get "a, b, c and d". I can replace it afterwards, or join all the names except the last one and add it separately, but maybe someone here has an elegant solution I'm not seeing? This is the best I can currently think of:
names.dropLast(1).joinToString(", ") + " and " + names.last()
g
No elegant solution, just use
if
condition for those 2 cases
Copy code
if (names.size < 2) {
   names.firstOrNull() ?: ""
} else {
  names.dropLast(1).joinToString(", ") + " and " + names.last()
}
it would be elegant enough if extract it to own extension function
m
That's pretty much the if statement I have, except I use
singleOrNull()
instead of
firstOrNull()
. Good idea with just moving that to an extension function, I will do that.
Copy code
fun List<String>.joinToString(separator: String, lastSeparator: String): String {
    return if (size > 1) {
        dropLast(1).joinToString(separator) + lastSeparator + last()
    } else {
        singleOrNull() ?: ""
    }
}
I'm happy with this. 🙂