For example suppose I have
for (line <- myData) {
println("}, {")
}
Is there a way to get the last line to print
println("}")
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.
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.
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.
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.
Can you refactor your code to take advantage of built-in mkString
?
scala> List(1, 2, 3).mkString("{", "}, {", "}")
res1: String = {1}, {2}, {3}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With