build.sbt, settings and tasks
build.sbt is not a properties file: it is Scala, evaluated by the build. A settingKey declares a value the build reads, a taskKey declares work the build runs, and libraryDependencies is a setting whose value is a list. The whole build below is four ideas on five lines, and sbt can run any of them by name.
A setting, a task and a dependency
greeting is a setting of type String, and showGreeting is a task of type Unit that reads it. The dependency line is the ordinary form: %% appends the Scala binary version to the artifact name, and % Test keeps the library out of the program's own class path:
build.sbt
scalaVersion := "3.10.1"
name := "banner"
libraryDependencies += "org.scalameta" %% "munit" % "1.3.6" % Test
val greeting = settingKey[String]("The word the program prints")
greeting := "hello from a task"
val showGreeting = taskKey[Unit]("Print the greeting during the build")
showGreeting := println(greeting.value)
lazy val root = (project in file("."))
.settings(name := "banner")
src/main/scala/Main.scala
@main def banner(): Unit =
println("Hello from sbt")
sbt showGreeting runs the task and prints what it printed. The clean; in front of it matters here: sbt caches the result of a task whose inputs did not change and skips it on the next call, so a page that shows the output asks for a fresh run. The welcome banner and the elapsed time of each call are left out of the quote:
sbt --server --batch "clean;showGreeting"
hello from a task
sbt compile compiles the program, and sbt run starts it. The build is a task graph: run depends on compile, compile depends on the class path the dependency line builds, and sbt runs only the nodes whose inputs changed. The same two commands as a reader types them:
sbt --server --batch compile
sbt --server --batch run
[info] running banner
Hello from sbt
A setting is evaluated once per build and a task once per invocation, which is the difference a custom task must respect: reading greeting.value inside a task is allowed, reading a task inside a setting is not. A build that needs a value for every module puts the setting in ThisBuild / ..., as the next lesson does with scalaVersion.
Related
- The sbt project layout: the folder these two files sit in.
- sbt tests and multiple modules: one build.sbt for several projects.
- scala-cli, directives and scripts: the same dependency declared in a comment instead of a build.
- Packaging: what a build produces when the program leaves the machine.
Article author: Arthur Isaev