0

I'm trying to figure out a smart way to comma separate a list, while the separator between the last two elements should be an and.

So for instance, I would like this string

listOf<Fruits>(Fruit.APPLE, Fruit.ORANGE, Fruit.BANANA)

to print out this:

"Apple, Orange and Banana"

Tried the simple joinToString, but that only allows a single separator, so that would just leave it comma separated all the way. Any smart way to do this? Haven't really been able to properly find an answer.

Mikkel Larsen
  • 876
  • 2
  • 14
  • 26
  • @khelwood I've never seen a more accurate dupe... until I looked at the question. I think there is some editing weirdness going on here. None of the answers seems to use "and". They all just join with commas. – Michael Sep 09 '19 at 08:03
  • @Michael Some of the answers also describe how to include "and" – khelwood Sep 09 '19 at 08:05
  • @khelwood there isn't really a solid answer there. At least one I can see, some of it is just plain untested code. – Mikkel Larsen Sep 09 '19 at 08:10
  • 2
    @MikkelLarsen [Bohemian's answer](https://stackoverflow.com/a/18742563/1898563) looks the best. I think what we can learn from this question is that there is no commonly available library method to do such a thing (and asking for library recommendations if off-topic anyway). You're right that it's untested... so add some tests :) – Michael Sep 09 '19 at 08:12
  • @Michael yeah I ended up using that, and works fine. Thanks for the help. – Mikkel Larsen Sep 09 '19 at 08:46
  • So many convoluted answers there, many which don't answer the part about including "and". Just join the last two items with `" and "` and then join it to the rest with` ", "`. – Tenfour04 Sep 10 '19 at 18:54

0 Answers0