Alex Rivera | Logout

Is there a way to handle the last case differently in a Scala for loop?

Asked 2011-08-22T07:24:00.123
18

For example suppose I have

  for (line <- myData) {
    println("}, {")
  }

Is there a way to get the last line to print

println("}")
Edit
Report

1 Answer

6

You may take the addString function of the TraversableOncetrait as an example.

def addString(b: StringBuilder, start: String, sep: String, end: String): StringBuilder = {
  var first = true

  b append start   
  for (x <- self) {
    if (first) {
      b append x
      first = false
    } else {
      b append sep
      b append x
    }
  }
  b append end

  b
}

In your case, the separator is }, { and the end is }

answered 2011-08-22T07:41:47.280

Your Answer