How to read from standard input line by line?

后端 未结 6 580
走了就别回头了
走了就别回头了 2020-12-22 17:19

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 cla         


        
6条回答
  •  自闭症患者
    2020-12-22 17:33

    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]())
    }
    

提交回复
热议问题