如何在 sbt 控制台中加载 scala 文件? [英] How to load a scala file in the sbt console?

查看:60
本文介绍了如何在 sbt 控制台中加载 scala 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我像这样启动 sbt 控制台:

I start the sbt console like this:

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) 文件,内容如下:

I have a test.scala (/home/alex/projects/test.scala) file with something like this:

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

如何做到这一点,以便我可以在控制台中执行这样的操作:

How to do it so that I can do something like this in the console:

scala> timesTwo

并输出函数的值?

推荐答案

简而言之,使用 scala REPL 中的 :load 函数来加载文件.然后你可以在文件中调用该函数,如果你将它包装在一个对象或类中,因为 sbt 试图编译它.不确定你是否可以只用一个函数定义来完成.

In short, use the :load function in the scala REPL to load a file. Then you can call that function in the file if you wrap it in an object or class since sbt tries to compile it. Not sure if you can do it with just a function definition.

将它包装在一个 object 中,让 sbt 正确编译它.

Wrap it in an object to get sbt to compile it correctly.

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 中,则可以使用 :paste 命令将其粘贴到scala REPL/sbt 控制台.

If you want just the function definition without wrapping it in a class or object the you can paste it with the command :paste in the scala REPL/sbt console.

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

这可以只通过函数名调用.

This can be called by just the function name.

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

这篇关于如何在 sbt 控制台中加载 scala 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆