Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

For example suppose I have

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

Is there a way to get the last line to print

println("}")
like image 256
deltanovember Avatar asked Aug 22 '11 07:08

deltanovember


People also ask

How does for loop work in Scala?

In Scala, for loop is also known as for-comprehensions. A for loop is a repetition control structure which allows us to write a loop that is executed a specific number of times. The loop enables us to perform n number of steps together in one line.

How to return value from for loop in Scala?

For-Loop with Yield In Scala, the loop's return value is stored in a variable or may return through a function. To do this, you should prefix the body of the 'for' expression with the keyword yield.

How many ways we can use for loop in Scala?

You can use multiple ranges separated by semicolon (;) within for loop and in that case loop will iterate through all the possible computations of the given ranges. Following is an example of using just two ranges, you can use more than two ranges as well.

Should I use for loops in Scala?

Learning loops to get familiar with Scala is bad. It's as if you wanted to learn French but still pronounce the 'h'. You need to let it go. If loops are one of the first things you learn in Scala, that will validate all the other concepts you might have encountered in other languages.


2 Answers

Can you refactor your code to take advantage of built-in mkString?

scala> List(1, 2, 3).mkString("{", "}, {", "}")
res1: String = {1}, {2}, {3}
like image 105
Tomasz Nurkiewicz Avatar answered Nov 15 '22 18:11

Tomasz Nurkiewicz


Before going any further, I'd recommend you avoid println in a for-comprehension. It can sometimes be useful for tracking down a bug that occurs in the middle of a collection, but otherwise leads to code that's harder to refactor and test.

More generally, life usually becomes easier if you can restrict where any sort of side-effect occurs. So instead of:

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

You can write:

val lines = for (line <- myData) yield "}, {"
println(lines mkString "\n")

I'm also going to take a guess here that you wanted the content of each line in the output!

val lines = for (line <- myData) yield (line + "}, {")
println(lines mkString "\n")

Though you'd be better off still if you just used mkString directly - that's what it's for!

val lines = myData.mkString("{", "\n}, {", "}")
println(lines)

Note how we're first producing a String, then printing it in a single operation. This approach can easily be split into separate methods and used to implement toString on your class, or to inspect the generated String in tests.

like image 43
Kevin Wright Avatar answered Nov 15 '22 17:11

Kevin Wright