Scala Question Regarding readLine

Patrick Jayet
Jul 10, 2010 · 1 min read

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).

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

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

[code]
(1 to 3) foreach {
i => println(Console.readLine)
}
[/code]

Any idea why?

XRB’s Blog

Random thoughts of a Software Engineer

Patrick Jayet

Written by

Polyglot (FR, DE, EN, ES), polyglot programmer (Java, Groovy, Ruby, Swift, Objective-C, Scala, Python, O’Caml) polyglot methodologist (Scrum, Kanban, Lean).

XRB’s Blog

Random thoughts of a Software Engineer