13

If I have two separate uncompiled scala files in the same directory as:

// hello.scala
object hello {
  def world() = println("hello world")
}

and:

// do.scala
hello.world()

I get an error when running do.scala:

$ scala do.scala
error: not found: value hello

Instead I have to compile the hello.scala file first and put it on the classpath to get it to work:

$ scalac hello.scala
$ scala -cp hello do.scala
hello world

Is there a way to get one script to call the other uncompiled scala file using the right use of import, package, classpath, the scala command line tool or something else?

1

3 Answers 3

8

Maybe not exactly what you're looking for, but from the Scala REPL shell you can do

:load hello.scala
:load do.scala

to achieve the same result:

$ scala
Welcome to Scala version 2.9.1 (Java HotSpot(TM) Server VM, Java 1.6.0_26).
Type in expressions to have them evaluated.
Type :help for more information.

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

scala> :load do.scala
Loading do.scala...
hello world

scala> 

If you're wanting something non-interactive for scripting

$ cat <<EOF | scala
:load hello.scala
:load do.scala
EOF

works too.

Use :help for more interesting things the REPL shell can do.

Sign up to request clarification or add additional context in comments.

3 Comments

Interesting. If I had other jars I needed to call from the code could I use the same trick but with "cat <<EOF | scala -cp jarfile.jar"?
Doing this or just "cat myreplcommandsfile | scala" works but makes my shell unusable after that annoyingly.
I note there is another REPL trick ':cp <path>' which claims to allow you to add a jar or a directory to the classpath. And yes I noticed it did something horrible to my xterm state after it finished too but I thought it was just me. Not sure what the fix for that is; simply redirecting output doesn't seem to help.
2

Looking into on the fly compilation/embedding the compiler. Twitter's util-eval is one such example.

1 Comment

Util-eval is removed.
0

You can just put

:load /path/file

at the first line in the file you are going to load.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.