SBT basics
Sbt is the de facto build tool in the Scala community.
Being used to other build tools you will be familiar with the commands
- clean – Deletes files produced by the build, such as generated sources, compiled classes, and task caches.
- compile – Compiles sources
- test – Executes all tests
- package – Produces the main artifact, such as a binary jar. This is typically an alias for the task that actually does the packaging.
- help – Displays this help message or prints detailed help on requested commands (run ‘help ‘).
- console – Starts the Scala interpreter with the project classes on the classpath.
Then we have extra commands suchs as
- run – Runs a main class, passing along arguments provided on the command line.
- tasks – Lists the tasks defined for the current project.
- reload – (Re)loads the current project or changes to plugins project or returns from it.
- console – Starts the Scala interpreter with the project classes on the classpath.
A key functionality is the new command.
For example by using new, we can create a project from the template specified (for example scala-seed.g8) using giter8.
sbt new scala/scala-seed.g8 ... Minimum Scala build. name [My Something Project]: hello Template applied in ./hello
The previous snippet creates a project called hello.
The file build.sbt holds a sequence of key-value pairs called setting expressions. The left-hand side is a key and the right hand side is the body.
There are three types of keys.
- SettingKey[T]: a key for a value computed once (the value is computed
when loading the subproject, and kept around). - TaskKey[T]: a key for a value, called a task, that has to be recomputed
each time, potentially with side effects. - InputKey[T]: a key for a task that has command line arguments as input.
For example if we want to add and extra task, to our previous project, which prints hello, then we shall add the following lines to the build.sbt file.
import Dependencies._ lazy val hello = taskKey[Unit]("An example task") lazy val root = (project in file(".")). settings( hello := { println("Hello!") }, inThisBuild(List( organization := "com.example", scalaVersion := "2.12.2", version := "0.1.0-SNAPSHOT" )), name := "Hello", libraryDependencies += scalaTest % Test )
We can either run the task or ask for more info about the task.
>sbt > hello Hello! [success] Total time: 0 s, completed May 1, 2017 6:08:36 PM > help hello An example task >
Depending on the project and the plugin used, there would be extra tasks and settings defined.
On the next post we will check play and sbt integration, and some basic commands.
Reference: | SBT basics from our JCG partner Emmanouil Gkatziouras at the gkatzioura blog. |