【问题标题】:How to start a Scala method from command line?如何从命令行启动 Scala 方法?
【发布时间】:2012-08-16 00:27:55
【问题描述】:

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

我编译了以下文件Test.scala

package example

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

}

scalac Test.scala.

然后,我可以分两步运行printscala 方法:

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 的回答以使其在没有 import 语句的情况下工作

【问题讨论】:

  • scala -e ... 在我的 Mac 上运行良好。嗯……scala -e "import example._; example.Test.print"呢?
  • @ArikG 你明白了。这适用于我的 Windows 7 安装程序。谢谢。

标签: scala console


【解决方案1】:

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

scala -e 'example.Test.print'

请尝试:

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

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

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

【讨论】:

  • 非常感谢。你的解决方案奏效了——太好了。但这让我有点吃惊。我在C:\User\John\Scala\Examples 目录下触发了scala -e "example.Test.print",因此Scala 应该找到与包匹配的底层目录èxample。我怎么了?
  • @JohnThreepwood 只有在当前目录位于“默认”类路径中时才能找到它。试试bash -x scala -e "example.Test.print" 看看它是否将任何类路径传递给java。如果没有,则没有默认的类路径。
【解决方案2】:

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

package example

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

仍然可以向它添加方法,对象的主体在启动时执行。

【讨论】:

  • 谢谢。编译后,我可以用scala example.Test 运行它。这个解决方案的缺点是,我必须将我想使用的方法封装在一个扩展 App 的单独类中。但是,它仍然是一个很好的解决方案。
【解决方案3】:

给你:

scala -e 'example.Test.print'

【讨论】:

    猜你喜欢
    • 2018-10-19
    • 1970-01-01
    • 2015-01-29
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    相关资源
    最近更新 更多