Free Handbook · Every example compiled & verified

Scala Handbook

Learn Scala the way it is written at work. Seventeen modules from your first program to a job: every example program was compiled and run with Scala 3 before publishing, with its output shown exactly as it printed, and the real compiler errors and runtime exceptions you will hit are explained with the fix. Values and types, expressions and match, functions and recursion, classes, objects and traits, case classes and pattern matching, collections, higher-order functions, Option, Either and Try, generics and givens, Futures and concurrency, debugging, Scala with sbt, MUnit, Apache Spark, Kafka, PostgreSQL, Redis, AWS, Docker and GitHub Actions, data structures and algorithms, problem-solving patterns, interview questions, a certification exam, and a resume check at the end.

0 / 142 lessons🔥 0 day streak
ShareXLinkedIn

How this handbook works

Every lesson has a complete Scala program with the exact output it prints — each one compiled and run with the real Scala toolchain before it was published, so what you see is what you will get when you run it yourself — a trace of what the program did line by line where that matters, and the real compiler or runtime error you will hit next, with why it happened and the fix. Lessons tick themselves as you go. Finish the handbook, sit the exam, get the certificate, then take your resume through the ATS checker against a real job posting.

17modules
142lessons
133compiled examples
56real errors explained

Module 00 · what you'll be able to do

  • Explain what Scala is, how it runs on the JVM, and where it is used in data engineering and backends
  • Install Scala 3 on macOS, Windows or Linux with Coursier and check it with scala version
  • Run a single-file program with scala run, open the REPL, and create an sbt project
  • Read the structure of a Scala 3 file: @main, def, val, indentation and comments
  • Know the practical differences between Scala 2 and Scala 3 and which one a Spark job uses
01

Why learn Scala

Scala is a statically typed language that mixes object-oriented and functional programming. Martin Odersky designed it at EPFL in Switzerland, and it was first released in 2004. Scala compiles to JVM bytecode, so a Scala program runs anywhere Java runs and can call any Java library directly — the whole Java ecosystem is available on day one.

What makes Scala feel different is how little ceremony it needs. Types are inferred, almost everything is an expression that returns a value, functions are values you pass around, and immutable data is the default. You get the safety of a strict compiler with code that often reads as short as Python.

  • Data engineering — Apache Spark is written in Scala, and its Scala API is the most complete one. Spark jobs, Delta Lake and Iceberg pipelines, and Databricks notebooks are a large share of Scala jobs. See the Spark Scala functions handbook and the Data Engineering course.
  • Streaming — Apache Kafka started life in Scala and its broker still has Scala code; Kafka Streams, Flink and Akka/Pekko Streams all have Scala APIs used in real-time pipelines.
  • Backends — fintech, ad-tech and trading firms build high-throughput services with Play, http4s, ZIO, Cats Effect and Akka/Pekko.
  • Compilers and tooling — Scala's type system makes it popular for DSLs, code generators and internal platforms.
RoleWhere Scala shows upWhat to learn after this handbook
Data engineerSpark batch and streaming jobs, Delta/Iceberg tables, DatabricksSpark DataFrames and Datasets, SQL, Airflow
Big-data platform engineerKafka, Flink, custom Spark libraries and connectorsJVM tuning, Kafka internals, Kubernetes
Backend developerAPIs and event-driven services in fintech and ad-techhttp4s or Play, Cats Effect or ZIO, Postgres
Functional programmerLibraries, DSLs, type-safe internal platformsCats, type classes, effect systems
In real jobs
Most Scala job ads are really "Spark + Scala" data engineering roles. The interviews test exactly what this handbook covers: immutability, case classes, pattern matching, collections, Option, higher-order functions and Future — plus reading a Spark stack trace without panicking.
02

Scala 2 vs Scala 3

Scala 3 (released 2021) is a rewrite of the compiler with a cleaner syntax. This handbook teaches Scala 3. You will still meet Scala 2.12 and 2.13 in the wild — Apache Spark is built on Scala 2.13 (and older clusters on 2.12) — so wherever the syntax differs, the lesson shows the Scala 2 form too. The good news: the concepts are the same, and most Scala 2 code compiles in Scala 3 unchanged.

FeatureScala 2Scala 3
Program entry pointobject Main { def main(args: Array[String]): Unit = ... }@main def run(): Unit = ... (the Scala 2 form still works)
BlocksBraces { } requiredBraces optional — indentation works, like Python
if / whileif (x > 0) ...if x > 0 then ... (parentheses still allowed)
Enumerationssealed trait + case objectsenum Color { case Red, Green }
Implicitsimplicit val, implicit defgiven and using
Top-level definitionsMust live inside an objectdef and val allowed at the top of a file
Which one does Spark use?
Spark 3.x and 4.x are compiled for Scala 2.12/2.13, so a Spark project sets scalaVersion := "2.13.x". Everything in modules 01–08 of this handbook works in Scala 2.13 with braces and parentheses; the few Scala 3-only features (enums, given, top-level def) are flagged where they appear.
03

Install Scala on macOS, Windows and Linux

The official installer is Coursier (cs). Its cs setup command installs a JDK if you do not have one, plus scala (the runner, which is scala-cli under the hood), scalac, sbt and scalafmt, and puts them on your PATH.

bashmacOS (Homebrew)
brew install coursier
coursier setup

# open a new terminal, then check
scala version
bashLinux (x86-64)
curl -fL https://github.com/coursier/coursier/releases/latest/download/cs-x86_64-pc-linux.gz | gzip -d > cs
chmod +x cs
./cs setup

# open a new terminal, then check
scala version
powershellWindows (PowerShell)
# download and unzip the Windows launcher
Invoke-WebRequest -Uri "https://github.com/coursier/coursier/releases/latest/download/cs-x86_64-pc-win32.zip" -OutFile cs.zip
Expand-Archive cs.zip -DestinationPath .
.\cs-x86_64-pc-win32.exe setup

# open a new terminal, then check
scala version
text
Scala code runner version: 1.16.0
Scala version (default): 3.9.0

What a working install prints (your version numbers may be newer).

Already use SDKMAN or Homebrew for Java?
sdk install scala (SDKMAN) or brew install scala also give you the Scala 3 runner. Any of these is fine — what matters is that scala version prints a 3.x version.
"scala: command not found" after installing
The installer edited your shell profile, but the terminal you already had open never re-read it. Close the terminal and open a new one. If it still fails, run cs setup again and accept the prompt to update PATH, or add ~/.local/share/coursier/bin (Linux) / ~/Library/Application Support/Coursier/bin (macOS) to PATH yourself.

For an editor, use IntelliJ IDEA with the Scala plugin, or VS Code with the Metals extension. Both understand sbt and scala-cli projects, show type hints and errors as you type, and run @main methods with one click.

04

Your first Scala program

Create a folder, save this as Main.scala, then run scala run Main.scala in that folder. The first run downloads the compiler, so it is slow; after that it takes a few seconds.

scalaMain.scala
@main def hello(): Unit =
  println("Hello, Scala!")
  println(2 + 3)
Outputcompiled & run with real Scala
Hello, Scala!
5
Your turn

Add a third line that prints your name, and a fourth that prints 10 * 4.

  1. 1
    1. @main

    Marks hello as the program's entry point. The name is yours to choose — run, hello, app.

  2. 2
    2. def hello(): Unit

    def defines a method. (): means it takes no parameters, and Unit is the return type — "returns nothing useful", like void in Java.

  3. 3
    3. = and indentation

    The body follows =. In Scala 3 the indented lines under it are the body; no braces needed.

  4. 4
    4. println

    Prints a value followed by a newline. It works with any type: strings, numbers, lists, your own classes.

bash
scala run Main.scala     # compile (if changed) and run
scala compile Main.scala # compile only — shows errors
scala run .              # run every .scala file in the folder

What happens behind scala run: scala-cli compiles Main.scala to JVM bytecode in a hidden .scala-build folder, then starts a JVM and calls your @main method.

Error you will hit

Type mismatch — a string where a number was expected

scala
@main def run(): Unit =
  val age: Int = "42"
  println(age)
-- [E007] Type Mismatch Error: Main.scala:2:17
2 |  val age: Int = "42"
  |                 ^^^^
  |                 Found:    ("42" : String)
  |                 Required: Int
1 error found
Compilation failed
Why the compiler said that

Scala checks every type before the program runs. "42" is text, and the declared type Int is a number — the compiler refuses instead of guessing. Read a Scala error top-down: the header gives the error code, file, line and column; the caret points at the exact expression; Found is what you wrote, Required is what the context needed.

The fix

Write a number literal, or convert the text on purpose with .toInt.

scala
@main def run(): Unit =
  val age: Int = 42
  println(age)
05

How a Scala program is structured

A Scala 3 file can hold definitions at the top level: methods (def), values (val), classes, traits and objects. One method marked @main is where execution starts. Everything else is called from there.

scalaMain.scala
// a top-level method: takes a name, returns a String
def greet(name: String): String =
  s"Hello, $name"

val language = "Scala"

@main def run(): Unit =
  println(greet("Priya"))
  println(greet(language))
  val total = 3 * 7
  println(s"3 * 7 = $total")
Outputcompiled & run with real Scala
Hello, Priya
Hello, Scala
3 * 7 = 21
Your turn

Write a second method shout(name: String): String that returns name.toUpperCase + "!", and print shout("scala").

The same program in the Scala 2 style, which still compiles in Scala 3 and is what you will see in most Spark code: an object with a main method that receives the command-line arguments.

scalaMain.scala
object Main {
  def greet(name: String): String = {
    s"Hello, $name"
  }

  def main(args: Array[String]): Unit = {
    println(greet("Priya"))
    println(s"args given: ${args.length}")
  }
}
Outputcompiled & run with real Scala
Hello, Priya
args given: 0

Braces and indentation can be mixed freely in Scala 3; a team usually picks one style and enforces it with scalafmt.

ThingConventionExample
Values, variables, methodscamelCasetotalPrice, parseLine
Classes, traits, objects, enumsPascalCaseOrderService, Shape
ConstantsPascalCase (or UPPER_CASE from Java habits)val MaxRetries = 3
Packageslowercase, dottedcom.acme.pipeline
FilesNamed after the main class/object insideOrderService.scala

The REPL

Type scala (or scala repl) with no file to open the REPL — a prompt that evaluates each line and prints its value and type. It is the fastest way to check what an expression does.

text
scala> val xs = List(1, 2, 3)
val xs: List[Int] = List(1, 2, 3)

scala> xs.map(_ * 10)
val res0: List[Int] = List(10, 20, 30)

scala> :quit

The REPL shows the inferred type of every value — a free lesson in type inference.

06

Real projects: scala-cli and sbt

scala-cli (the scala command) is perfect for scripts, single files and learning. Library dependencies go in a comment directive at the top of the file:

scalaMain.scala
//> using scala 3.3.6
//> using dep com.lihaoyi::os-lib:0.11.4

@main def run(): Unit =
  println(os.pwd)

sbt is the standard build tool for multi-file projects, libraries and Spark jobs. A project is a folder with a build.sbt and sources under src/main/scala; tests go in src/test/scala.

bash
sbt new scala/scala3.g8   # scaffold a project (asks for a name)
cd hello-world
sbt run                   # compile and run
sbt test                  # run tests
sbt ~compile              # recompile on every save
scalabuild.sbt
ThisBuild / scalaVersion := "3.3.6"

lazy val root = project
  .in(file("."))
  .settings(
    name := "hello-world",
    libraryDependencies += "org.scalameta" %% "munit" % "1.0.0" % Test
  )

%% appends the Scala version to the artifact name (munit_3), because Scala libraries are published per Scala version. A Spark project sets scalaVersion to 2.13.x and adds "org.apache.spark" %% "spark-sql".

scala-cli

  • One file or a folder, zero config
  • Dependencies in //> using comments
  • Great for scripts, learning, quick tools
  • Can package a runnable JAR or native binary

sbt

  • Multi-module projects
  • build.sbt, plugins, publishing
  • Standard for libraries, services and Spark jobs
  • Incremental compiler and continuous mode
07

Comments

Scala has the same three comment styles as Java. // runs to the end of the line, /* ... */ spans lines, and /** ... */ is a Scaladoc comment that documentation tools and your IDE show as hover help.

scalaMain.scala
/** Returns the area of a rectangle.
  * @param w width
  * @param h height
  */
def area(w: Int, h: Int): Int = w * h

@main def run(): Unit =
  // a single-line comment
  println(area(3, 4)) // can follow code too
  /* a block comment
     println("this never runs") */
  println("done")
Outputcompiled & run with real Scala
12
done
Comment the why, not the what
// add one above n + 1 is noise. // the API counts pages from 1 is worth keeping, because the code cannot say it.
08

How this handbook works

Seventeen modules, each its own page, from your first val to a job-ready resume. The rail on the left lists them; the bar at the top and the pill at the bottom-left track your progress. A lesson ticks itself when you reach its end, and the tick survives closing the tab — no account needed.

  • Examples are compiled and verified. Scala cannot run inside a web page, so every example here is a complete program that was compiled and run with real Scala 3 before publishing. The output under it is exactly what it printed — save it as Main.scala and run scala run Main.scala to see the same thing.
  • "Your turn" tasks under each example ask you to change one thing. Predict the output first, then run it.
  • Traces step through a program line by line with the values at each step — used for loops, recursion, pattern matching and folds.
  • Error cards show the real scalac or JVM message, why it happened, and the fix. Module 11 collects the fifteen most common.
  • Interview questions appear where the topic is taught and are collected in Module 15.
  • The handbook ends with a certification exam (25 questions, 70% to pass), then the ATS resume checker with a real job posting.
The floating board
The pill at the bottom-left opens a board with every key term from the module you are on and a tutor you can ask about the code on the page. It is a language model — check what it says against the real compiler.
ModulesYou learn
01–03val and var, types, strings, expressions, match, loops, for-comprehensions, methods and functions
04–05Classes, objects, traits, enums, case classes, pattern matching, ADTs
06–08Collections, higher-order functions, Option, Either and Try
09–10Generics, givens and type classes, Futures and concurrency
11–14Debugging, Scala with real tools (sbt, Spark, Kafka, Docker…), data structures and algorithms, problem solving
15–16Sixty interview questions, resume, portfolio, the certificate
09

Using AI to learn Scala (without cheating yourself)

An AI assistant will happily write a chain of map, flatMap and foldLeft for you. That is exactly why you should write them yourself while learning. The goal is the model in your head: what type each step returns, why a for-comprehension is just flatMap, why a match is exhaustive. That model is what an interviewer probes and what lets you debug a Spark job that failed at 3 a.m.

Do this

  • Paste a real compiler error and ask what it means, then fix it yourself
  • Ask "what is the type of this expression?" after making your own guess
  • Write the function first, then ask for a review of style and edge cases
  • Ask it to turn your loop into a fold — then explain each step back to it

Not this

  • Ask for the answer to a "Your turn" task and paste it in
  • Accept code with implicits or givens you cannot explain
  • Silence a pattern-match warning because the AI suggested @unchecked
  • Use it during an interview or the certification exam

Ready? Module 01 starts with val and var, types, strings and reading keyboard input.

Every lesson in the handbook

17 modules · 142 lessons · each one ticks itself when you reach the end.

00Getting Started0 / 9
01Fundamentals0 / 6
02Expressions & Control0 / 8
03Functions0 / 8
04Classes, Objects & Traits0 / 8
05Case Classes & Pattern Matching0 / 8
06Collections0 / 8
07Higher-Order Functions0 / 7
08Option, Either & Try0 / 7
09Generics & Givens0 / 7
10Futures & Concurrency0 / 9
11Errors & Debugging0 / 7
12Scala + Tools0 / 10
13Data Structures & Algorithms0 / 12
14Problem Solving0 / 12
15Interview Questions0 / 10
16Job Ready0 / 6

Frequently asked questions

Is this Scala handbook free?
Yes — every module, every example and the certification exam are free, with no signup and no paywall. The exam asks you to sign in with Google so the certificate can carry your name.
Do I need to know another programming language first?
No, Module 01 starts from values and types and assumes nothing, although Scala is easier if you have written some code before. If you know Java, Kotlin or Python, the handbook calls out where Scala differs: everything is an expression, == compares values, immutability is the default, and missing values and errors are handled with Option and Either instead of null and exceptions.
Do I need to install anything?
Yes — a JDK and Scala, and Module 00 shows how to install them on macOS, Windows and Linux and run your first program. The examples on this page do not run in the browser; instead, each example program was compiled and run with Scala 3 before publishing, and the output shown is exactly what it printed, so you can paste it into Main.scala, run scala run Main.scala and get the same result. The labs in Module 12 need libraries and services such as Spark, Kafka and PostgreSQL, so they are shown as clearly marked snippets.
Scala 2 or Scala 3: which does this handbook teach?
Scala 3, with every example verified on it, including the new syntax, enums, givens and extension methods, opaque types and union types. Because many Spark codebases still run Scala 2.12 or 2.13, the handbook shows the Scala 2 equivalents where they differ, so you can read and work in both.
Is there a certificate?
Yes. Pass the 25-question exam (35 minutes) with 70% or more and generate a SolutionGigs Scala certificate with your name, score, date and a certificate ID — download it, print it or add it to LinkedIn.
Is Scala hard to learn?
The basics — values, methods, classes, collections — are no harder than Java or Python, and the syntax is shorter than Java. Scala gets harder when you reach advanced functional libraries and type-level programming, which most jobs (especially Spark data engineering) do not require. Modules 01–08 of this handbook cover what a Spark or backend role expects.
Do I need Java before learning Scala?
No. Knowing Java helps because Scala runs on the JVM and uses Java libraries, but this handbook assumes only that you have written some code in any language. If you have never programmed, start with the Python handbook first.
Should I learn Scala 2 or Scala 3?
Learn Scala 3 — it is the current language and its syntax is cleaner. The concepts are identical, and this handbook shows the Scala 2 form wherever it differs, because Spark projects still compile with Scala 2.13. Switching between them takes a day, not a month.

Finish the Scala handbook, then get hired

Sit the exam for your certificate, run your resume through the ATS checker, and see the jobs that ask for exactly this.

Check my resume
Found this course useful? Share it.
ShareXLinkedIn

Comments

0

Join the conversation. Sign in to leave a comment — we'd love to hear your thoughts.