scalac, java -cp and Java side by side

scala-cli is the convenient path, not the only one. The compiler is scalac, and its output is a folder of class files that the java command runs — the same two steps javac and java take for Java. A build server, an IDE and a production image all end at this point.

scalac and java -cp

The compiler writes class files into the folder -d names, and it refuses a folder that does not exist, so the first command creates it:

Main.scala

@main def main(): Unit = val names = List("Ada", "Grace") println(names.mkString(", ")) println(java.time.LocalTime.MIDNIGHT)

mkdir -p out
scalac -color:never -d out Main.scala
java -cp "out:/opt/scala/lib/*" main

Ada, Grace
00:00

The class path has two entries: the folder just written, and the Scala library, which lives in /opt/scala/lib in a standard installation and nowhere on the default class path of the JVM. Without the second entry the run fails with NoClassDefFoundError: scala/collection/immutable/List, because the program uses the standard library of Scala, not only of Java. -color:never keeps a diagnostic plain when it is captured; without it the compiler writes colour codes into a redirected log.

Inside the class file

javap reads the class file back. The entry point is a real static main, which is why the JVM can start it:

javap -p -cp out main

Compiled from "Main.scala"
public final class main {
  public main();
  public static void main(java.lang.String[]);
}

A top-level definition becomes a class of the package: the file Main.scala produced main.class for the entry point and Main$package.class for the rest of the file. That name is an implementation detail, and it is the reason a Scala class can be called from Java only through a definition with a stable name: an object.

Java calls Scala

An object compiles to a class with a static field MODULE$ and a static forwarder for each method, so Java sees an ordinary static method. The two files below are one program: Scala defines the method, Java calls it.

Greeter.scala

object Greeter: def greet(name: String): String = s"Hello, $name"

Main.java

public class Main { public static void main(String[] args) { System.out.println(Greeter.greet("Java")); System.out.println(Greeter.greet("Scala")); } }

mkdir -p out2
scalac -color:never -d out2 Greeter.scala
javac -cp "out2:/opt/scala/lib/*" -d out2 Main.java
java -cp "out2:/opt/scala/lib/*" Main

Hello, Java
Hello, Scala

The order matters: javac reads Greeter.class, so the Scala file is compiled first. The reverse direction needs no step at all — the Java library is what a Scala program imports — which is why the interoperability lesson of the last chapter goes further into the details.

Related

Article author: Arthur Isaev