Scala nondeterministic / caches classes?
Asked Answered
G

1

13

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.

Gil answered 20/3, 2014 at 15:32 Comment(1)
Agree, reproducible on OSX 10.8.3, scala 2.10.3Paperboard
S
8

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
Subsellium answered 20/3, 2014 at 16:52 Comment(1)
Would not have figured that out in a million years. Very sneaky ... thanks!Gil

© 2022 - 2024 — McMap. All rights reserved.