A String.join(List) for Scala using reduceLeft
Now and again when working with text files I run into the need of having to concatenate a bunch of strings with some separator in between (say a comma). In languages such as Python you typically have a join() method on String that allows you to do this: the string is the separator and the parameter to join is a list or iterable of some sort.
Scala doesn't seem to have such a method on String, or at least I couldn't find one.
The bare metal Java way to solve this tiny problem - a for loop with an index where you can check whether you reached the end or not - doesn't seem very Scala-like at all.
But there is an alternative that looks better: reduceLeft. This is one of those mysterious functional idioms that are sprinkled all over Scala and that seem apocryphal to the lowly imperative programmer (myself included!).
reduceLeft is a method on List that takes an anonymous function with 2 arguments (a lambda) as a parameter and then applies that function to the first element of the list and the second element, then to the result of that application and the third element, etcetera etcetera. This gives us a neat way to implement join in Scala:
val someList = List("foo", "bar", "baz", "qux")
val concatenated = someList.reduceLeft(_ + ", " + _)Now concatenated contains "foo, bar, baz, qux". Note that I used the shortcut syntax for the anonymous function, you can also write it out:
val concatenated = someList.reduceLeft( (x1: String, x2: String) => x1 + ", " + x2)
But why would you?
Update 1.12.2009: Or you could just use the mkString method on Iterable. Doh! I totally missed that.
