316

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 ",").

aknuds1
  • 65,625
  • 67
  • 195
  • 317
scala_newbie
  • 3,435
  • 2
  • 12
  • 13

1 Answers1

505

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.

Magnus Reftel
  • 967
  • 6
  • 19
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • Note that the foldLeft implementation assumes a non-empty list – Ferdy Oct 24 '15 at 21:20
  • 8
    Thanks! In case anyone wants to enclose string elements in quotes, mkString is also helpful: theStrings.mkString("'", "','", "'") – Niko Gamulin Aug 23 '16 at 13:20
  • 1
    @Frawr That page links to a bunch of examples https://oldfashionedsoftware.com/2009/07/30/lots-and-lots-of-foldleft-examples/ which includes an implementation that uses pattern matching for the empty list (Nil) case. Modifying it to mimic mkString would be like this: `def mkFoldLeftString[A](list:List[String], delim:String = ","): String = list match { case head :: tail => tail.foldLeft(head)(_ + delim + _) case Nil => "" }` – Davos Jul 11 '17 at 14:37
  • 3
    The langref.org link is dead – Floegipoky Mar 09 '18 at 22:43