18.2. Compiling, Running, and Packaging a Scala Project with SBT
Problem
You want to use SBT to compile and run a Scala project, and package the project as a JAR file.
Solution
Create a directory layout to match what SBT expects, then run
sbt compile
to compile your project,
sbt run
to run your project, and
sbt package
to package your project
as a JAR file.
To demonstrate this, create a new SBT project directory structure as shown in Recipe 18.1, and then create a file named Hello.scala in the src/main/scala directory with these contents:
package
foo.bar.baz
object
Main
extends
App
{
println
(
"Hello, world"
)
}
Unlike Java, in Scala, the file’s package name doesn’t have to match the directory name. In fact, for simple tests like this, you can place this file in the root directory of your SBT project, if you prefer.
From the root directory of the project, you can compile the project:
$ sbt compile
Run the project:
$ sbt run
Package the project:
$ sbt package
Discussion
The first time you run SBT, it may take a while to download all the dependencies it needs, but after that first run, it will download new dependencies only as needed. The commands executed in the Solution, along with their output, are shown here:
$sbt compile
[info] Loading global plugins from /Users/Al/.sbt/plugins [info] Set current project to Basic (in build file:/Users/Al/SbtTests/) [success] Total time: 0 s $sbt run
[info] Loading global plugins from /Users/Al/.sbt/plugins [info] Set current project to Basic (in build file:/Users/Al/SbtTests/) ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.