SBT Basics
In this lesson, you will learn about SBT, the official build tool for Scala. SBT is used to compile code, manage dependencies, and run Scala projects efficiently.
Almost all real-world Scala projects use SBT, so understanding it is essential for professional Scala development.
What Is SBT?
SBT stands for Simple Build Tool. It automates common development tasks such as:
- Compiling Scala code
- Managing external libraries
- Running applications
- Packaging projects
SBT is highly optimized for incremental compilation, making builds faster.
Why Scala Uses SBT
Scala projects often grow large and complex. SBT helps by:
- Handling project structure automatically
- Downloading required dependencies
- Rebuilding only changed files
This improves developer productivity and project stability.
Basic SBT Project Structure
A typical SBT project follows a standard directory structure.
my-project/
├── build.sbt
├── project/
│ └── build.properties
└── src/
└── main/
└── scala/
└── Main.scala
Each part of this structure has a specific purpose.
The build.sbt File
The build.sbt file defines project settings such as name, version, and dependencies.
name := "MyScalaProject"
version := "0.1.0"
scalaVersion := "2.13.12"
This configuration tells SBT how to build the project.
Adding Dependencies
Dependencies are external libraries your project relies on.
They are added inside build.sbt.
libraryDependencies +=
"org.typelevel" %% "cats-core" % "2.10.0"
SBT automatically downloads the library and makes it available to your project.
Writing a Simple Scala Program
Let’s create a basic Scala file inside the SBT project.
object Main {
def main(args: Array[String]): Unit = {
println("Hello from SBT project")
}
}
This file is placed inside src/main/scala.
Running an SBT Project
Open a terminal inside the project directory and run:
sbt run
SBT compiles the code and runs the program automatically.
Common SBT Commands
Here are some frequently used SBT commands:
sbt compile– Compiles the projectsbt run– Runs the applicationsbt test– Runs testssbt clean– Cleans build files
Interactive SBT Shell
You can start the interactive SBT shell by typing:
sbt
Inside the shell, you can run commands faster without restarting SBT.
Why SBT Is Important
SBT simplifies:
- Project setup
- Dependency management
- Build automation
Mastering SBT is essential for working on real Scala applications.
📝 Practice Exercises
Exercise 1
Create a new SBT project and add a project name.
Exercise 2
Write a Scala program and run it using SBT.
Exercise 3
Add a dependency to build.sbt.
✅ Practice Answers
Answer 1
name := "SampleProject"
Answer 2
object App {
def main(args: Array[String]): Unit = {
println("Running with SBT")
}
}
Answer 3
libraryDependencies +=
"org.scalatest" %% "scalatest" % "3.2.17"
What’s Next?
In the next lesson, you will learn about the Scala Workflow, including compiling, running, and organizing real-world Scala projects.