ggreeppy
ggreeppy

Reputation: 89

Concatenating a list of strings

Is there a built in method to take all of the strings in a list of strings and concatenate them in Scala? If not, how would I do this?

Upvotes: 2

Views: 3544

Answers (2)

Ben Reich
Ben Reich

Reputation: 16324

You might be looking for mkString:

List("a", "b").mkString //"ab"

The method also takes in an argument which joins the elements:

List("a", "b").mkString(" ") //"a b"

Without this method, you could use the more primitive reduce:

List("a", "b") reduceLeft { (soFar, next) => soFar + next }
List("a", "b").reduceLeft(_+_)

Or even the more primitive foldLeft:

List("a", "b").foldLeft("")(_+_)
("" /: List("a", "b"))(_+_)

Upvotes: 7

elm
elm

Reputation: 20435

An additional note on mkString, you can delimit the beginning and the end of the appended strings, for instance as follows,

scala> val x = List("a","b","c")
x: List[String] = List(a, b, c)

scala> x.mkString("<", "-", ">")
res0: String = <a-b-c>

Upvotes: 3

Related Questions