5

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 that way?

My best attempt so far is:

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 it is quite cumbersome. Any idea?

Mikaël Mayer
  • 10,425
  • 6
  • 64
  • 101

1 Answers1

15
val init = l.view.init

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

init returns all elements except the last one, view allows you to get init without creating a copy of collection.

For empty collection head (and last) will throw an exception, so you should use headOption and lastOption if you can't prove that your collection is not empty.

senia
  • 37,745
  • 4
  • 88
  • 129
  • I did not know about init and last. Even if it is not algorithmically efficient to use them, they are useful in that case. – Mikaël Mayer Dec 21 '13 at 20:31