Marcin Wisniowski
12/06/2018, 2:07 AMjoinToString(", ")
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()
gildor
12/06/2018, 2:16 AMif
condition for those 2 casesgildor
12/06/2018, 2:18 AMif (names.size < 2) {
names.firstOrNull() ?: ""
} else {
names.dropLast(1).joinToString(", ") + " and " + names.last()
}
gildor
12/06/2018, 2:19 AMMarcin Wisniowski
12/06/2018, 2:20 AMsingleOrNull()
instead of firstOrNull()
. Good idea with just moving that to an extension function, I will do that.Marcin Wisniowski
12/06/2018, 2:24 AMfun 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. 🙂