291
votes

How do I "join" an iterable of strings by another string in Scala?

val thestrings = Array("a","b","c")
val joined = ???
println(joined)

I want this code to output a,b,c (join the elements by ",").

1
@scala_newbie I think your question was downvoted, 'cause some people think it lacks of research effort.om-nom-nom
googling this question is my research effortWalrus the Cat

1 Answers

464
votes

How about mkString ?

theStrings.mkString(",")

A variant exists in which you can specify a prefix and suffix too.

See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.