这是一个简单的程序.我希望main以解释模式运行.但是另一个物体的存在导致它什么都不做.如果QSort不存在,该程序将执行.
main当我在REPL中运行它时为什么不调用?
object MainObject{
def main(args: Array[String])={
val unsorted = List(8,3,1,0,4,6,4,6,5)
print("hello" + unsorted toString)
//val sorted = QSort(unsorted)
//sorted foreach println
}
}
//this must not be present
object QSort{
def apply(array: List[Int]):List[Int]={
array
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:抱歉导致混淆,我正在运行脚本scala filename.scala.
Uta*_*aal 14
如果参数to scala是现有的.scala文件,它将在内存中编译并运行.当存在单个顶级对象时,将搜索主方法,并且如果找到则执行.如果不是这种情况,则顶级语句将包含在合成主方法中,而后者将被执行.
这就是删除顶级QSort对象允许运行main方法的原因.
如果你要将它扩展为一个完整的程序,我建议编译并运行(使用类似的构建工具sbt)编译的.class文件:
scalac main.scala && scala MainObject
Run Code Online (Sandbox Code Playgroud)
如果您正在编写单个文件脚本,只需删除main方法(及其对象)并在外部作用域中编写要执行的语句,如:
// qsort.scala
object QSort{
def apply(array: List[Int]):List[Int]={
array
}
}
val unsorted = List(8,3,1,0,4,6,4,6,5)
print("hello" + unsorted toString)
val sorted = QSort(unsorted)
sorted foreach println
Run Code Online (Sandbox Code Playgroud)
并运行: scala qsort.scala
该scala命令用于执行scala"脚本"(单个文件程序)和复杂的类似Java的程序(在类路径中具有主对象和一堆类).
来自man scala:
The scala utility runs Scala code using a Java runtime environment.
The Scala code to run is specified in one of three ways:
1. With no arguments specified, a Scala shell starts and reads com-
mands interactively.
2. With -howtorun:object specified, the fully qualified name of a
top-level Scala object may be specified. The object should pre-
viously have been compiled using scalac(1).
3. With -howtorun:script specified, a file containing Scala code
may be specified.
Run Code Online (Sandbox Code Playgroud)
如果未明确指定,howtorun则从传递给脚本的参数中猜出模式.
当给定对象的完全限定名称时,scala将猜测-howtorun:object并期望路径上具有该名称的编译对象.
否则,如果参数to scala是现有的.scala文件,-howtorun:script则猜测并且如上所述选择入口点.
小智 11
对象模块的任何方法都可以在REPL中运行,方法是显式指定它并为其提供所需的参数(如果有的话).例如:
scala> object MainObject{
| def main(args: Array[String])={
| val unsorted = List(9,3,1,0,7,5,9,3,11)
| print("sorted: " + unsorted.sorted)
| }
| def fun = println("fun here")
| }
defined module MainObject
scala> MainObject.main(Array(""))
sorted: List(0, 1, 3, 3, 5, 7, 9, 9, 11)
scala> MainObject.fun
fun here
Run Code Online (Sandbox Code Playgroud)
在某些情况下,这对快速测试和故障排除很有用.