Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Scala script reference other uncompiled scala code in the same directory?

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?

like image 207
user1305156 Avatar asked Apr 04 '12 12:04

user1305156


People also ask

How do I run a scala program from the command line?

Here is the full process from the command line: evan@vbox ~> cat test. scala object test{ def main(args: Array[String]): Unit = println("Hello!") } evan@vbox ~> scalac test. scala evan@vbox ~> scala test Hello!

How do I run a scala script from the console?

Executing Scala code as a script Another way to execute Scala code is to type it into a text file and save it with a name ending with “. scala”. We can then execute that code by typing “scala filename”. For instance, we can create a file named hello.

Which command is used to compile and run scala program?

To compile the code, type "scalac hello_world. scala" and press enter.


2 Answers

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.

like image 181
timday Avatar answered Oct 17 '22 02:10

timday


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

like image 36
pr1001 Avatar answered Oct 17 '22 02:10

pr1001