【问题标题】:How to load a scala file in the sbt console? [duplicate]如何在 sbt 控制台中加载 scala 文件? [复制]
【发布时间】:2012-12-16 17:54:00
【问题描述】:

可能重复:
Load Scala file into interpreter to use functions?

我这样启动 sbt 控制台:

alex@alex-K43U:~/projects$ sbt console
[info] Set current project to default-8aceda (in build file:/home/alex/projects/)
[info] Starting scala interpreter...
[info] 
Welcome to Scala version 2.9.2 (OpenJDK Client VM, Java 1.6.0_24).
Type in expressions to have them evaluated.
Type :help for more information.

scala>

我有一个 test.scala (/home/alex/projects/test.scala) 文件,内容如下:

def timesTwo(i: Int): Int = {
  println("hello world")
  i * 2
}

如何做到这一点,以便我可以在控制台中做这样的事情:

scala> timesTwo

并输出函数的值?

【问题讨论】:

  • 这不是重复的。 sbt console 在启动时编译源文件,所以你只需要Times timesTwo 7。 (我把它包裹在像 Brian 这样的 Times 对象中。巧合还是命运?)
  • 同意。这不是重复的。 sbt 和 scala 控制台在这方面的行为不同。

标签: scala sbt


【解决方案1】:

简而言之,使用 scala REPL 中的:load 函数来加载文件。然后,如果您将其包装在对象或类中,则可以在文件中调用该函数,因为sbt 会尝试编译它。不确定您是否可以仅使用函数定义来做到这一点。

将其包裹在 object 中以获取 sbt 以正确编译它。

object Times{
  def timesTwo(i: Int): Int = {
    println("hello world")
    i * 2
  }
}

加载文件:

 scala> :load Times.scala
 Loading Times.scala...
 defined module Times

然后在Times中调用timesTwo

 scala> Times.timesTwo(2)
 hello world
 res0: Int = 4

如果您只想要函数定义而不将其包装在 classobject 中,您可以在 scala REPL/sbt 控制台中使用命令 :paste 将其粘贴。

scala> :paste
// Entering paste mode (ctrl-D to finish)

def timesTwo(i: Int): Int = {
  println("hello world")
  i * 2
}

// Exiting paste mode, now interpreting.

timesTwo: (i: Int)Int

这可以通过函数名来调用。

 scala> timesTwo(2)
 hello world
 res1: Int = 4

【讨论】:

  • 怎么知道从哪里加载,默认目录是什么
  • @Mike 你在scala 中运行的目录。
  • 如何指定目录?我不能给它一个路径
  • @Mike :load /path/to/file.txt 这样的东西应该可以工作。
  • ` import com._` 定义开始非法,不是自动导入依赖吗?
猜你喜欢
  • 2012-09-24
  • 2019-04-26
  • 2015-12-28
  • 1970-01-01
  • 2013-04-30
  • 1970-01-01
  • 2013-06-06
  • 1970-01-01
  • 2011-07-13
相关资源
最近更新 更多