Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a jar file from scala

Tags:

jar

scala

sbt

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!")
}
like image 911
odbhut.shei.chhele Avatar asked Jun 01 '15 14:06

odbhut.shei.chhele


People also ask

How do you make a jar in 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.

Does Scala use jar?

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.

How do I create a Scala jar in IntelliJ?

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.


2 Answers

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.

like image 68
elm Avatar answered Sep 21 '22 04:09

elm


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.

like image 27
shutty Avatar answered Sep 21 '22 04:09

shutty