可能重复:将
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
并输出函数的值?
Bri*_*ian 17
简而言之,使用:loadscala REPL中的函数来加载文件.然后,如果将它包装在对象或类中,则可以在文件中调用该函数,因为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
然后调用timesTwo在Times:
 scala> Times.timesTwo(2)
 hello world
 res0: Int = 4
如果你只想要函数定义而不将它包装在一个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
| 归档时间: | 
 | 
| 查看次数: | 8961 次 | 
| 最近记录: |