Q:

Scala: Print separators when using output stream

When we need an array of strings to be concatenated, we can use mkString method:
val concatenatedString = listOfString.mkString

However, when we have a very long list of string, getting concatenated string may not be a good choice. In this case, It would be more appropriated to print out to an output stream directly, Writing it to output stream is simple:
listOfString.foreach(outstream.write _)

However, I don't know a neat way to append separators. One thing I tried is looping with an index:
var i = 0
for(str <- listOfString) {
  if(i != 0) outstream.write ", "
  outstream.write str
  i += 1
}

This works, but it is too wordy. Although I can make a function encapsules the code above, I want to know whether Scala API already has a function do the same thing or not.
Thank you.

A:

Here is a function that do what you want in a bit more elegant way:
def commaSeparated(list: List[String]): Unit = list match {
    case List() => 
    case List(a) => print(a)
    case h::t => print(h + ", ")
                 commaSeparated(t)
}

The recursion avoids mutable variables.
To make it even more functional style, you can pass in the function that you want to use on each item, that is:
def commaSeparated(list: List[String], func: String=>Unit): Unit = list match {
    case List() => 
    case List(a) => func(a)
    case h::t => func(h + ", ")
                 commaSeparated(t, func)
}

And then call it by:
commaSeparated(mylist, oustream.write _)

A:

Self Answer:
I wrote a function encapsulates the code in the original question:
implicit def withSeparator[S >: String](seq: Seq[S]) = new {
  def withSeparator(write: S => Any, sep: String = ",") = {
    var i = 0
    for (str <- seq) {
      if (i != 0) write(sep)
      write(str)
      i += 1
    }
    seq
  }
}

You can use it like this:
listOfString.withSeparator(print _)

The separator can also be assigned:
listOfString.withSeparator(print _, ",\n")

Thank you for everyone answered me. What I wanted to use is a concise and not too slow representation. The implicit function withSeparator looks like the thing I wanted. So I accept my own answer for this question. Thank you again.

