Scala mkString, except for the last

I would like to do the following in scala:

val l = List("An apple", "a pear", "a grapefruit", "some bread")
... some one-line simple function ...
"An apple, a pear, a grapefruit and some bread"

What would be the shortest way to write it this way?

My best attempt:

def makeEnumeration(l: List[String]): String = {
  var s = ""
  var size = l.length
  for(i <- 0 until size) {
    if(i > 0) {
      if(i != size - 1) { s += ", "
      } else s += " and "
    }
    s += l(i)
  }
  s
}

But this is rather cumbersome. Any idea?

+4
source share
1 answer
val init = l.view.init

val result =
  if (init.nonEmpty) {
    init.mkString(", ") + " and " + l.last
  } else l.headOption.getOrElse("")

initreturns all elements except the last one, viewallows you to get initwithout creating a copy of the collection.

For an empty set head(s last) throws an exception, so you must use headOptionand lastOptionif you cannot prove that your collection is not empty.

+14
source

All Articles