11

可能重复:
将 Scala 文件加载到解释器中以使用函数?

我像这样启动 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

并输出函数的值?

4

1 回答 1

17

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

将其包装在 anobject中以sbt正确编译它。

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

加载文件:

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

然后调用timesTwoTimes

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

如果您只想要函数定义而不将其包装在 a 中,class或者object您可以使用:pastescala REPL/sbt 控制台中的命令将其粘贴。

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
于 2012-12-16T09:47:34.613 回答