I have read online that it is possible to create a jar file from scala code that could be run from the cli. All have written is the following code. How do I make a jar file from it? I am using sbt 0.13.7.
object Main extends App {
println("Hello World from Scala!")
}
Create a jar file using 'sbt assembly' command. If you run 'sbt assembly' command before adding plugin it shows errors. 2. Distribute all the JAR files necessary with a script that builds the classpath and executes the JAR file with the scala commands.
The scala runtime is just a jar file (scala-library. jar), you can get it here (look for the scala binaries for your platform). Copy scala-library. jar into the lib/runtime folder for the example code to work.
IntelliJ IDEA enables creation of JAR as an artifact of a project. Do the following steps. From the Project Structure window, navigate to Artifacts > the plus symbol + > JAR > From modules with dependencies.... In the Create JAR from Modules window, select the folder icon in the Main Class text box.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With