Packaging
A program that leaves the machine is a jar. scala-cli package turns a folder of sources into one, and --assembly puts the Scala library and every dependency inside it, so the jar runs with a JDK and nothing else. The alternative is a jar that names its dependencies beside it, which is what a build server publishes; the assembly is the form a reader downloads and runs.
The program and its entry point
The directive //> using mainClass greeting names the class the jar starts, which a folder with more than one @main would otherwise have to have chosen for it:
greeting.scala
//> using mainClass greeting
@main def greeting(name: String): Unit =
println(s"Hello, $name!")
scala-cli run --server=false greeting.scala -- Ada
Hello, Ada!
scala-cli --power package --assembly --server=false -o greeting.jar .
Wrote <PROJECT>/greeting.jar, run it with
./greeting.jar
The second line of the output is the command that runs the jar. The file is executable, so ./greeting.jar Ada starts it the same way, and java -jar is the form a script uses. The jar starts with the JDK directly, with no scala-cli and no compiler on the machine:
java -jar greeting.jar Ada
Hello, Ada!
java -jar is the form to use in a script or a unit file; the executable form is a launcher the packaging writes for a reader who double-clicks. The assembly is a few megabytes because the Scala library travels inside it, which is the price of a jar that needs nothing but a JDK.
What is not shown here
A plain scala-cli package without --assembly writes a much smaller jar whose manifest points at the dependency cache, so it runs only on a machine that has that cache. Publishing to a repository, signing, and a native image built with GraalVM are three further outputs of the same sub-command; each needs a network or a toolchain that a reader installs, so none of them is shown with an output here.
A build with several modules packages each module as a library and the program as an assembly of the whole graph, which is the same command in the build's own terms: sbt assembly comes from a plugin, and sbt package, which ships with the build, writes the library jar.
Related
- scala-cli, directives and scripts: the runner the packaging belongs to.
- sbt tests and multiple modules: the build that packages a graph rather than one folder.
- Java interoperability: the jar is a JVM artifact, so a Java program can call into it.
- The finishing project: a tool that ends at a jar of this shape.
Автор статьи: Arthur Isaev