The most straight-forward looking approach will just use readLine() which is part of Predef. however that is rather ugly as you need to check for eventual null value:
object ScannerTest {
def main(args: Array[String]) {
var ok = true
while (ok) {
val ln = readLine()
ok = ln != null
if (ok) println(ln)
}
}
}
this is so verbose, you'd rather use java.util.Scanner instead.
I think a more pretty approach will use scala.io.Source:
A recursive version (the compiler detects a tail recursion for improved heap usage),
def read: Unit = {
val s = scala.io.StdIn.readLine()
println(s)
if (s.isEmpty) () else read
}
Note the use of io.StdIn from Scala 2.11 . Also note with this approach we can accumulate user input in a collection that is eventually returned -- in addition to be printed out. Namely,
import annotation.tailrec
def read: Seq[String]= {
@tailrec
def reread(xs: Seq[String]): Seq[String] = {
val s = StdIn.readLine()
println(s)
if (s.isEmpty()) xs else reread(s +: xs)
}
reread(Seq[String]())
}
// Read STDIN lines until a blank one
import scala.io.StdIn.readLine
var line = ""
do {
line = readLine()
println("Read: " + line)
} while (line != "")