Scala:如何在按下 Ctrl-d 时停止程序

Scala : How to stop a program when Ctrl-d is pressed

如何通过按 Ctrl-d 停止类似 REPL 的控制台应用程序,而无需等待用户键入 Ctr-d 然后输入?

这是一个代码示例:

def isExit(s: String): Boolean = s.head.toInt == 4 || s == "exit"

def main(args: Array[String]) = {
    val continue: Boolean = true
    while(continue){
        println "> "
        io.StdIn.readLine match {
            case x if isExit(x) => println "> Bye!" ; continue = false
            case x              => evaluate(x) 
        }
    }
}

s.head.toInt == 4是测试输入行的第一个字符是否为ctrl d。

编辑:运行 的完整源代码:

object Test {

    def isExit(s: String): Boolean = s.headOption.map(_.toInt) == Some(4) || s == "exit"

    def evaluate(s: String) = println(s"Evaluation : $s")

    def main(args: Array[String]) = {
        var continue = true
        while(continue){
            print("> ")
            io.StdIn.readLine match {
                case x if isExit(x) => println("> Bye!") ; continue = false
                case x              => evaluate(x)
            }
        }
    }
}

有了这个,我在 s.headOption 上得到了一个 NullPointerException(因为 null s)

对代码进行少量修改

def main(args: Array[String]) = {
    var continue: Boolean = true // converted val to var
    while(continue){
        println("> ")
        io.StdIn.readLine match {
            case x if isExit(x) => println("> Bye!") ; continue = false
            case x              => evaluate(x) 
        }
    }
}

您的 isExit 方法没有处理您的读取行可能为空的情况。所以修改后的 isExit 看起来像下面这样。否则你的例子会按预期工作

def isExit(s: String): Boolean = s.headOption.map(_.toInt) == Some(4) || s == "exit"

好的,如中所述 Read Input until control+d Ctrl-D 按键将行刷新到 JVM 中。 如果在线上有写的东西,它会被发送(只有连续两次ctrl-d,我不知道为什么),否则io.StdIn.readLine会收到一个流结束字符并且会return null,如 Scala 文档中所示 http://www.scala-lang.org/api/2.12.0/scala/io/StdIn$.html#readLine():String

了解这一点,我们可以用简单的 s == null 替换 s.headOption... 来满足我们的需要。 完整的工作示例:

object Test {

    def isExit(s: String): Boolean = s == null || s == "exit"

    def evaluate(s: String) = println(s"Evaluation : $s")

    def main(args: Array[String]) = {
        var continue = true
        while(continue){
            print("> ")
            io.StdIn.readLine match {
                case x if isExit(x) => println("Bye!") ; continue = false
                case x              => evaluate(x)
            }
        }
    }
}