Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 37 ยท Tools and Ecosystem

sbt and Scala Project Setup

Set up Scala 3 projects with sbt: directory layout, build.sbt, dependencies with %%, compiler options, tasks, multi-module builds, plugins, and Scala CLI as a lighter option.

A single .scala file is fine for learning, but real programs need a build tool: something that downloads libraries, compiles code, runs tests and packages the result. The standard tool for Scala is sbt (the "simple build tool"). Alternatives are Mill, Gradle and Maven, and for small scripts there is Scala CLI. This lesson focuses on sbt, because most Scala projects and tutorials use it.

You need a JDK (17 or newer) installed first. sbt itself downloads the right Scala compiler for your project, so you never install the compiler separately.

Project layout

sbt follows the same convention as Maven. Source files go in fixed folders, so no configuration is needed to find them:

TEXT
my-app/
  build.sbt
  project/
    build.properties
    plugins.sbt
  src/
    main/
      scala/        application code (.scala files)
      resources/    config files, assets
    test/
      scala/        test code
      resources/

You can create a starter project with a template: sbt new scala/scala3.g8. The result is the layout above with a Main.scala file.

Bash Scaffold the layout in the shell (Bash, a stand-in for sbt new)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

(This only creates the files. The runner has no sbt or Scala compiler, so you would run sbt run on your own computer.)

build.sbt

The build definition is Scala code, but it reads like configuration. Each setting is key := value:

SCALA
ThisBuild / scalaVersion := "3.3.5"
ThisBuild / organization := "com.example"
ThisBuild / version := "0.1.0"

lazy val root = (project in file("."))
  .settings(
    name := "my-app",
    libraryDependencies ++= Seq(
      "org.typelevel" %% "cats-core" % "2.12.0",
      "org.scalameta" %% "munit" % "1.0.2" % Test
    ),
    scalacOptions ++= Seq(
      "-deprecation",     // explain deprecation warnings
      "-feature",         // explain language feature warnings
      "-Wunused:all",     // warn about unused imports, locals, params
      "-Werror"           // turn warnings into errors (consider for CI only)
    )
  )

What to notice:

  • ThisBuild / applies a setting to the whole build, which is useful once there are several modules.
  • scalaVersion := "3.3.5" chooses Scala 3.3 (the long-term-support line). Use the same version across a team.
  • libraryDependencies lists libraries as "group" %% "artifact" % "version". The double %% appends the Scala binary version to the artifact name, so munit becomes munit_3. Scala libraries are compiled separately for each major version (2.13, 3), and %% picks the right one. A single % is for plain Java libraries such as "org.postgresql" % "postgresql" % "42.7.4".
  • % Test limits a dependency to test code only.
  • scalacOptions configures the compiler. Warnings are valuable, such as the exhaustiveness check from Enums and Sealed ADTs.

Reading a dependency line

Group org.typelevel, who publishes it.
%% means Scala Adds _3 or _2.13 to the name.
Artifact cats-core, the library.
Version 2.12.0. Pin it.
1 / 2

Commands you will use daily

Start sbt once; it opens a shell that keeps the compiler warm, so later commands are fast:

Command What it does
compile Compile main sources
run Run the program (the @main function or main method)
test Run all tests
testOnly *UserSpec Run matching test classes
~test Re-run tests whenever a file changes
console Open the Scala REPL with your project on the classpath
reload Re-read build.sbt after editing it
dependencyTree Show the dependency graph (sbt 1.4+)
package Build a JAR
clean Delete build output

In CI you usually run one-shot commands: sbt "clean; test".

The REPL and worksheets

sbt console (or scala with the standalone launcher) gives an interactive prompt where you can paste snippets and try ideas. IDEs add worksheets, files that evaluate each line and show the result next to it. These are the quickest way to explore the standard library.

Dependencies that a project often needs

Need Typical library
Testing munit, ScalaTest, specs2
JSON circe, play-json, upickle, jsoniter-scala
HTTP server/client http4s, Pekko HTTP, Play, sttp
Functional toolkit cats, cats-effect, ZIO
Database Doobie, Slick, Quill, JDBC
CLI parsing scopt, decline
Logging slf4j + logback, scribe

Many of these appear again in Testing in Scala and Java Interop and Libraries.

Multi-module builds

When code grows, split it into modules that depend on each other:

SCALA
lazy val core = (project in file("core"))
  .settings(name := "core")

lazy val api = (project in file("api"))
  .dependsOn(core)
  .settings(name := "api", libraryDependencies += "org.http4s" %% "http4s-ember-server" % "0.23.30")

lazy val root = (project in file("."))
  .aggregate(core, api)

dependsOn lets api use code from core. aggregate makes commands on root run in every module. Each module has its own src/main/scala.

flowchart TD
    R["root (aggregate)"] --> C["core"]
    R --> A["api"]
    A -->|dependsOn| C

Plugins

Plugins extend sbt. They go in project/plugins.sbt:

SCALA
addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.5.2")        // code formatting
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.3.0")         // one fat JAR
addSbtPlugin("com.github.sbt" % "sbt-native-packager" % "1.10.4") // Docker images, installers

Formatting configuration lives in a .scalafmt.conf file in the project root; a minimal one is version = "3.8.3" and runner.dialect = scala3. Run scalafmtAll to format everything, and scalafmtCheckAll in CI.

Scala CLI: scripts and small programs

For a single file, a script or a quick experiment, Scala CLI needs no build file. You put settings in comments at the top of the file:

SCALA
//> using scala 3.3.5
//> using dep com.lihaoyi::os-lib:0.11.3

@main def listFiles(): Unit =
  os.list(os.pwd).foreach(p => println(p.last))

Run it with scala-cli run listFiles.scala. Here :: plays the same role as %%. Scala CLI can also compile, test, package and format, and is what the scala command launches in recent installers. When a script grows into a real project, move its settings into build.sbt.

Library versions and binary compatibility

Scala 3 can use Scala 2.13 libraries (.cross(CrossVersion.for3Use2_13)), but Scala 2 libraries that use macros may not work. Library authors use semantic versioning and Scala projects check "binary compatibility" with a tool called MiMa. As a user, you mostly need to remember: keep versions pinned, upgrade deliberately, and read release notes for major upgrades.

Version strings in action

The second stand-in below (Bash, not Scala) mimics how %% forms an artifact name and the path where it is stored in a Maven-style repository, the mechanism sbt uses behind the scenes.

Bash How %% builds an artifact name (Bash, a stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Common mistakes

  • Using % instead of %% for a Scala library, which gives "not found: munit" errors.
  • Forgetting reload after editing build.sbt in a running sbt shell.
  • Mixing Scala binary versions (a 2.13 library and a 3 library that both expect different dependencies).
  • Leaving -Werror on during development. It is great in CI but annoying while you experiment.
  • Putting tests in src/main. Tests belong in src/test/scala so they do not ship in the JAR.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does %% do in an sbt dependency?

    %% turns munit into munit_3 (or munit_2.13), selecting the build for your Scala version. A single % is for Java libraries.
  2. 2. Where do test sources go in a standard sbt project?

    Test code lives in src/test/scala by convention, and sbt finds it automatically.
  3. 3. Which command re-runs the tests every time you save a file?

    A tilde prefix makes sbt repeat a command whenever sources change.
  4. 4. When is Scala CLI a better choice than sbt?

    Scala CLI configures a file through using directives and needs no build definition.

Summary

  • sbt is the standard Scala build tool; it uses fixed folders and a build.sbt written as Scala settings.
  • Dependencies are "group" %% "artifact" % "version"; %% selects the artifact for your Scala version, % Test limits scope.
  • Daily commands: compile, run, test, ~test, console, reload.
  • Split big projects into modules with dependsOn and aggregate; add plugins in project/plugins.sbt.
  • Scala CLI handles scripts and small programs with comment directives.

Next: Testing in Scala