我想改进Scala中的以下代码:
shouldContinue = true while (shouldContinue) { val input = StdIn.readLine() if (input == ":q") { shouldContinue = false // do things here } else { System.exit(1) } }
此程序期望 :q 退出。有没有可能 if (input == ":q") 但是一些内置的功能 :问 或 :quit ?
:q
if (input == ":q")
:问
:quit
您可以编写一个尾部递归函数,它不像while循环那样变异。可以避免使用var变量。
import scala.io.StdIn._ import scala.annotation.tailrec @tailrec def tailRecursiveCheck(shouldExit: Boolean): Unit = { if(shouldExit) System.exit(0) else { val s = readLine tailRecursiveCheck(s == ":q" || s == ":quit") } } tailRecursiveCheck(false)