I am new to Scala and try to use it in a functional way. Here are my questions:
Why can't I create a new binding for 'cnt' variable with function return value using '<-' operator?
How can increment immutable variable in a functional way (similar to Haskell <-) ? For the sake of experiment I don't want to use mutable vars.
import scala.io.Source object MyProgram { def main(args: Array[String]): Unit = { if (args.length > 0) { val lines = Source.fromFile(args(0)).getLines() val cnt = 0 for (line <- lines) { cnt <- readLines(line, cnt) } Console.err.println("cnt = "+cnt) } } def readLines(line: String, cnt:Int):Int = { println(line.length + " " + line) val newCnt = cnt + 1 return (newCnt) } }
As for side effects, I could never expect that (line <- lines) is so devastating! It completely unwinds lines iterator. So running the following snippet will make size = 0 :
val lines = Source.fromFile(args(0)).getLines()
var cnt = 0
for (line <- lines) {
cnt = readLines(line, cnt)
}
val size = lines.size
Is it a normal Scala practice to have well-hidden side-effects like this?