Recursive Requirements Between Scala And Java

Because of a great professor, I've gotten to use Scala instead of Java for my Advanced Data Structures and Analysis class this semester. He warned me I'd be on my own, and that provided materials would be in Java. I thought this would be simple because of Scala's interoperability with Java, and I was right.

For our last assignment, we were given the skeleton of a spreadsheet application, the GUI and some of the logic. We had to build the calculator that would parse expressions in the spreadsheet and find cycles in them. I became worried when I realized that my Calculator class, written in Scala, would require the SpreadSheet class, written in Java, and vice-versa. (I'm not claiming this is a good design, by the way. Between reusing an earlier calculator written in the class and not writing the GUI, the recursive requirements seemed the easiest way.)

I'd used Java classes already compiled as bytecode before, but never had to compile Java classes requiring my Scala code. It ended up being much easier than I expected.

From my Ant build.xml:

<target name="build" depends="prepare" description="Build source">
  <scalac srcdir="${path.src}" destdir="${path.build}">
    <classpath refid="build.classpath"/>
  </scalac>
  <javac srcdir="${path.src}" destdir="${path.build}">
    <classpath refid="build.classpath"/>
  </javac>
</target>

You can see that Scala code is compiled first. When I run ant build, though, I see this:

build:
   [scalac] Compiling 1 scala and 3 java source files to CMSC420/project4/build
    [javac] Compiling 3 source files to CMSC420/project4/build

scalac is not actually compiling the Java files, though, as you can easily test.

cnixon:(git)School[master]/CMSC420/project4/src$ scalac -verbose *.scala *.java
# ... tons of output elided
[parsing Calculator.scala]
[parsing CycleFoundException.java]
[parsing SpreadSheet.java]
[parsing SpreadSheetException.java]

When scalac parses the Scala code, it also parses the Java code, allowing the compiler to know what classes from Java will be available, even though they currently aren't.

Published: 12 Dec 2008