Question

I have a very simple goal: to compile a Scala class, and then load it from within another Scala script. The problem is that Scala seems to cache (not sure where) the classes that I create, and doesn't respect subsequent changes.

The following lines create a directory with two .scala files, compiles one, and runs the other:

mkdir test
cd test
echo 'class MyClass(s: String)' > MyClass.scala
echo 'val p = new MyClass("ok")' > test.scala
scalac MyClass.scala
scala test.scala # this works
cd ..
rm -rf test

If I run the above lines, I need to REBOOT MY COMPUTER for the lines below to work:

mkdir test
cd test
echo 'class MyClass()' > MyClass.scala
echo 'val p = new MyClass()' > test.scala
scalac MyClass.scala
scala test.scala # this doesn't
cd ..
rm -rf test

If I don't reboot, I get an error that I'm missing a String in my constructor. Not sure where in Scala-land it's caching the previous String-based constructor.

Was it helpful?

Solution

This is because the scala script runner starts a resident instance of the compile server (fsc) in the background. You should be able to find a running java process with main class scala.tools.nsc.CompileServer after running your first script.

Note that this only happens when scala is used to run a script, that is, a .scala file that does not contain a single compilation unit with a main class.

Subsequent calls to scala will use this compile server (only when used to run a script), which caches information about previous compilation runs, hence the error.

You can instruct scala not to use fsc when running a script with:

scala -nc test.scala

You can also shut down that background instance with:

fsc -shutdown

Or reset its cache with:

fsc -reset
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top