2

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?

2 Answers 2

7

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"))(_+_) 
Sign up to request clarification or add additional context in comments.

2 Comments

Shouldn't that also be reduceLeft?
Indeed, reduceLeft is what was intended. Fixed.
3

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> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.