如何从命令行启动Scala方法?

时间:2012-08-14 09:50:05

标签: scala console

这个问题可能听起来有点愚蠢,但我无法弄清楚,如何从命令行启动Scala方法。

我编译了以下文件Test.scala

package example

object Test {
  def print() {
    println("Hello World")
  }

}

scalac Test.scala

然后,我可以分两步使用print运行方法scala

C:\Users\John\Scala\Examples>scala
Welcome to Scala version 2.9.2 (Java HotSpot(TM) Client VM, Java 1.6.0_32).
Type in expressions to have them evaluated.
Type :help for more information.

scala> example.Test.print
Hello World

但我真正想做的是,使用scala example.Test.print之类的命令直接从命令行运行该方法。

我如何实现这一目标?

更新 ArikG建议的解决方案对我不起作用 - 我缺少什么?

C:\Users\John\Scala\Examples>scala -e 'example.Test.print'
C:\Users\John\AppData\Local\Temp\scalacmd1874056752498579477.scala:1: error: u
nclosed character literal
'example.Test.print'
         ^
one error found

C:\Users\John\Scala\Examples>scala -e "example.Test.print"
C:\Users\John\AppData\Local\Temp\scalacmd1889443681948722298.scala:1: error: o
bject Test in package example cannot be accessed in package example
example.Test.print
        ^
one error found

,其中

C:\Users\John\Scala\Examples>dir example
 Volume in drive C has no label.
 Volume Serial Number is 4C49-8C7F 

 Directory of C:\Users\John\Scala\Examples\example

14.08.2012  12:14    <DIR>          .
14.08.2012  12:14    <DIR>          ..
14.08.2012  12:14               493 Test$.class
14.08.2012  12:14               530 Test.class
               2 File(s)          1.023 bytes
               2 Dir(s)  107.935.760.384 bytes free

更新2 - 可能的解决方案:

  • 正如ArikG正确建议的那样,scala -e "import example.Test._; print"适用于Windows 7。
  • 如果没有导入声明,请参阅Daniel的回答以使其工作

3 个答案:

答案 0 :(得分:10)

让我稍微扩展一下这个解决方案:

scala -e 'example.Test.print'

相反,请尝试:

scala -cp path-to-the-target-directory -e 'example.Test.print'

目标目录是scala用作编译目标的目标的目录。在您的示例中,不是 C:\Users\John\Scala\Examples\example,而是C:\Users\John\Scala\Examples。目录example是Scala将查找属于 example的类的位置。

这就是为什么事情不起作用:它希望在目录示例下找到包example,但是在您运行scala的当前目录下没有这样的目录,并且类文件当前目录中存在的内容应该在默认包中。

答案 1 :(得分:6)

这样做的最好方法是扩展App这是一个稍微特殊的类(或者至少是它的基础上的DelayedInit):

package example

object Test extends App {
  println("Hello World")      
}

还可以为此添加方法,对象的主体在启动时执行。

答案 2 :(得分:4)

你走了:

scala -e 'example.Test.print'