How to make a jar file from scala
To be able to perform complex build tasks with Scala, you have to use SBT as a build tool: it's a default scala-way of creating application packages. To add SBT support to your project, just create a build.sbt
file in root folder:
name := "hello-world"
version := "1.0"
scalaVersion := "2.11.6"
mainClass := Some("com.example.Hello")
To build a jar file with your application in case if you have no external dependencies, you can run sbt package
and it will build a hello-world_2.11_1.0.jar
file with your code so you can run it with java -jar hello-world.jar
. But you definitely will have to include some dependencies with your code, at least because of a Scala runtime.
Use sbt-assembly plugin to build a fat jar with all your dependencies. To install it, add a line
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.12.0")
to your project/plugins.sbt
file (and create it if there's no such file) and run sbt assembly
task from console.
In addition to sbt
, consider also this plain command line,
scalac hello.scala -d hello.jar
which creates the jar file. Run it with
scala hello.jar
Also possible is to script the source code by adding this header
#!/bin/sh
exec scala -savecompiled "$0" "$@"
!#
and calling the main method with Main.main(args)
(note chmod +x hello.sh
to make the file executable). Here savecompiled
will create a jar file on the first invocation.