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?
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.
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.
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
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..
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With