문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top