How to read from standard input line by line?

Andrei Ciobanu picture Andrei Ciobanu · Jan 3, 2011 · Viewed 75.7k times · Source

What's the Scala recipe for reading line by line from the standard input ? Something like the equivalent java code :

import java.util.Scanner; 

public class ScannerTest {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            System.out.println(sc.nextLine());
        }
    }
}

Answer

itemState picture itemState · Jan 3, 2011

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:

object ScannerTest {
  def main(args: Array[String]) {
    for (ln <- io.Source.stdin.getLines) println(ln)
  }
}