Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala mkString except the last one

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?

like image 266
Mikaël Mayer Avatar asked Dec 19 '13 12:12

Mikaël Mayer


People also ask

How to use mkstring () method with a separator in Scala list?

Scala List mkString() method with a separator with example. Last Updated : 13 Aug, 2019; The mkString() method is utilized to display all the elements of the list in a string along with a separator. Method Definition: def mkString(sep: String): String. Return Type: It returns all the elements of the list in a string along with a separator.

How to display all the elements of a list in Scala?

Scala List mkString () method with a separator with example. The mkString () method is utilized to display all the elements of the list in a string along with a separator. Return Type: It returns all the elements of the list in a string along with a separator.

How do I convert an int array to a string in Scala?

Converting a Scala Int array to a String. As a final example, you can also use the Scala mkString method to convert an Int array to a String, like this: scala> val numbers = Array(1,2,3) numbers: Array[Int] = Array(1, 2, 3) scala> val string = numbers.mkString(", ") string: String = 1, 2, 3

What is the use of mkstring in Java?

The mkString method has an overloaded method which allows you to provide a delimiter to separate each element in the collection. Furthermore, there is another overloaded method to also specify any prefix and postfix literal to be preprended or appended to the String representation..


1 Answers

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.

like image 77
senia Avatar answered Sep 29 '22 21:09

senia