How to make a jar file from scala

32,945

Solution 1

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.

Solution 2

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.

Solution 3

You can try this SBT plugin: https://github.com/sbt/sbt-native-packager

I created Linux Debian packages with this plugin (Windows MSI should be possible as well).

Solution 4

sbt: publishLocal then go to the target folder, probably called scala-2.**

Share:
32,945
odbhut.shei.chhele
Author by

odbhut.shei.chhele

আমাদের এই বাংলাদেশে ছিল তার বাড়ি কাউকে কিছু না বলে অভিমানে দূর দেশে দিল পারি

Updated on July 09, 2022

Comments

  • odbhut.shei.chhele
    odbhut.shei.chhele almost 2 years

    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!")
    }