可能的重复:
将 Scala 文件加载到解释器中以使用函数? https://stackoverflow.com/questions/7383436/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
并输出函数的值?
简而言之,使用:load
scala REPL 中的函数加载文件。然后,如果将其包装在对象或类中,则可以在文件中调用该函数,因为sbt
尝试编译它。不确定是否可以仅使用函数定义来完成此操作。
将其包裹在一个object
to get sbt
才能正确编译它。
object Times{
def timesTwo(i: Int): Int = {
println("hello world")
i * 2
}
}
加载文件:
scala> :load Times.scala
Loading Times.scala...
defined module Times
然后打电话timesTwo
in Times
:
scala> Times.timesTwo(2)
hello world
res0: Int = 4
如果您只想要函数定义而不将其包装在class
or object
您可以使用命令粘贴它:paste
在 scala 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)