11

Possible Duplicate:
Load Scala file into interpreter to use functions?

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>

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

And output the value of the function?

Community
  • 1
  • 1
alexchenco
  • 53,565
  • 76
  • 241
  • 413
  • 3
    This is not a duplicate. `sbt console` compiles the source file on start-up, so you only have to `Times timesTwo 7`. (I had wrapped it in a Times object like Brian. Coincidence or fate?) – som-snytt Dec 17 '12 at 00:49
  • 1
    Agreed. This is not a duplicate. sbt and scala consoles behave differently in this respect. – Synesso Jun 08 '17 at 00:26

1 Answers1

17

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.

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

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

Load the file:

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

Then call timesTwo in Times:

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

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
Brian
  • 20,195
  • 6
  • 34
  • 55