我正在学习Scala编程中的Scala。当我尝试运行本书中给出的代码时,它给出了以下错误:
Exception in thread "main" java.lang.RuntimeException: Cannot figure out how to run target: File2
at scala.sys.package$.error(package.scala:27)
at scala.tools.nsc.GenericRunnerCommand.scala$tools$nsc$GenericRunnerCommand$$guessHowToRun(GenericRunnerCommand.scala:38)
at scala.tools.nsc.GenericRunnerCommand$$anonfun$2.apply(GenericRunnerCommand.scala:48)
at scala.tools.nsc.GenericRunnerCommand$$anonfun$2.apply(GenericRunnerCommand.scala:48)
at scala.Option.getOrElse(Option.scala:108)
at scala.tools.nsc.GenericRunnerCommand.<init>(GenericRunnerCommand.scala:48)
at scala.tools.nsc.GenericRunnerCommand.<init>(GenericRunnerCommand.scala:17)
at scala.tools.nsc.MainGenericRunner.process(MainGenericRunner.scala:33)
at scala.tools.nsc.MainGenericRunner$.main(MainGenericRunner.scala:89)
at scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala)
我该如何解决这个问题?
这是我的代码:
object Files2 {
def filesHere = (new java.io.File(".")).listFiles
def filesMatching(query: String, matcher: (String, String) => Boolean) = {
for (file <- filesHere; if matcher(file.getName, query))
yield file
}
def filesEnding(query: String) = filesMatching(query, _.endsWith(_))
def filesContaining(query: String) = filesMatching(query, _.contains(_))
def filesRegex(query: String) = filesMatching(query, _.matches(_))
def main(args: Array[String]) {
println("filesEnding(\"scala\").toList [" + filesEnding("scala").toList + "]")
println("filesContaining(\"Files1\").toList [" + filesContaining("Files1").toList + "]")
println("filesRegex(\".*Re.ex.*\").toList [" + filesRegex(".*Re.ex.*").toList + "]")
}
}
答案 0 :(得分:3)
给定的文件不是脚本,它是一个简单的scala程序,你需要编译它然后运行它。错误是由于缺乏编译:
scalac Files2.scala
scala Files2
答案 1 :(得分:0)
我只是将您的代码粘贴到名为test.scala
的文件中,然后使用scala test.scala
运行它并且运行正常。
dhg ~$ scala test.scala
filesEnding("scala").toList [List(./test.scala)]
filesContaining("Files1").toList [List()]
filesRegex(".*Re.ex.*").toList [List()]