Question

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?

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top