I have a List defined as:
val l = List("1", "2", "3")
I want to convert it to the string
"1:2:3"
One way is the following:
l.foldLeft("")((x, y) => x + (if (x == "") "" else ":") +y)
Is there a more elegant method?
[EDIT: further explanation]
Easy Angel’s answer works when the elements of l have a ‘meaningful’ toString method.
although I have l as List[String], l can be a list of a custom type which does not override the toString method, say, as in:
class my(i:Int) {
val x = i
}
I have also a method
def getMy(m:my) = "Hello "+m.x
So I would like the output of getMy to be used instead of the output of the default toString method.
You can use
mkStringmethod ofList:More info can be found in scaladoc:
http://www.scala-lang.org/api/rc/scala/collection/Iterable.html#mkString:String
As alternative you can use
reduceLeftfor example:As an answer to your second question: Just combine it with
map: