An alternate to foldLeft that starts from second element
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 mkString
method of List
:
l mkString ":"
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 reduceLeft
for example:
l.reduceLeft(_ + ":" + _)
As an answer to your second question: Just combine it with map
:
l map getMy mkString ":"
another way to do this with just foldLeft:
l.tail.foldLeft(l.head)( (x, y) => x+":"+y )
The other suggestions are better, but when you want to keep foldLeft, you could use Options:
List("1","2","3").foldLeft(None:Option[String])((o,n)=> o.map(_+":"+n).orElse(Some(n))).get
//res2: String = 1:2:3
精彩评论