【发布时间】:2017-02-22 12:42:35
【问题描述】:
如何通过按 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)
【问题讨论】:
标签: scala read-eval-print-loop