Scala Question Regarding readLine

I have stumbled upon a weirdness regarding the behavior of readLine in Scala (at least with my current basic understanding of the language).

The following snippet is supposed to read three times a line from standard in. But it reads 3 times the same line (the first).

(1 to 3) foreach {
  val line = Console.readLine
  i => println(line)
}

while the following snippet (very similar) behaves as expected (reading the three first line from stdin):

(1 to 3) foreach {
  i => println(Console.readLine)
}

Any idea why?

5 thoughts on “Scala Question Regarding readLine”

  1. Hi!
    I’m definitely not a Scala expert, but…

    The problem with the first snippet is that the function you define is

    i => println(line)

    This is a closure which will be executed three times as expected. But it is closed to the line value which is read one time from the console.

    In the second snippet the function is

    i => println(Console.readLine)

    which is just executed three times.

  2. Oh, ok. I get it. So the val definition inside the closure is just executed once. I would have expected that it is executed each time the closure is executed. Thanks for the answer!

  3. Just noticed that the code is behaving as expected if the val definition is located in the second part of the closure:

    (1 to 3) foreach {
    i =>
    val line = Console.readLine
    println(line)
    }

  4. Sorry for my English, i’m just to unclear…

    the “line” is a value and cannot be executed, it is assigned only once from the result of the “Console.readLine” method execution. It is used than three times in your closure. But if you define it as a method, it will be executed three times:

    (1 to 3) foreach {
    def line = Console.readLine
    i => println(line)
    }

Comments are closed.