Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a scala file in the sbt console? [duplicate]

Tags:

scala

sbt

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?

like image 258
alexchenco Avatar asked Dec 16 '12 03:12

alexchenco


People also ask

How do I run a Scala file in CMD?

To run Scala from the command-line, download the binaries and unpack the archive. Start the Scala interpreter (aka the “REPL”) by launching scala from where it was unarchived. Start the Scala compiler by launching scalac from where it was unarchived.


1 Answers

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
like image 166
Brian Avatar answered Nov 10 '22 07:11

Brian