1. Up and running

The quickest way to get a feel for a language is to run some code, so we start by installing Scala and running a few small programs. After that I’ll describe two kinds of Scala codebase you could end up working in, which is what decides the order of this book.

1.1. Installing Scala

Scala runs on the JVM and needs JDK 17 or newer. Check what you have:

$ java -version

I ran the code in this book on JDK 25, the current long-term support release, but anything from 17 up will get you started.

The Scala project recommends installing through Coursier, its installer for Scala tools. Coursier’s command is cs, though Homebrew installs it under the longer name coursier. The setup command puts the scala command on your path, along with a JDK if it can’t find one already installed. On macOS with Homebrew:

$ brew install coursier && coursier setup

On Linux (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

Windows has an installer that you download and run. It’s linked from the official install page, https://docs.scala-lang.org/getting-started/install-scala.html, along with the commands for ARM machines.

Open a new terminal so that the changed path takes effect, then ask for the version:

$ scala version
Scala code runner version: 1.16.0
Scala version (default): 3.9.0

Your numbers will probably be higher than mine. Don’t worry about that, or about which JDK you have. Later in the chapter we add two lines to a source file saying which Scala and which JDK it wants, and the scala command downloads them if you don’t have them.

If you’ve looked at older tutorials, you may have seen them start by installing sbt, the main Scala build tool, and generating a project with it. You can skip all of that for now. Since Scala 3.5 the scala command has been a small build tool in its own right, one that compiles and runs your code and fetches whatever libraries the code asks for. The same program also goes by the name Scala CLI, and the “code runner version” in the output above is its version number. It’s all we need until chapter 18, where we move to sbt.

1.2. A first program

Make an empty directory to work in. I’ve called mine fully-booked, for reasons that will be clear in a few pages. In it, create a file called hello.scala:

@main def hello(): Unit =
  println("Hello from Scala")

Run it:

$ scala run hello.scala
Compiling project (Scala 3.9.0, JVM (25))
Compiled project (Scala 3.9.0, JVM (25))
Hello from Scala

The first run is slow while the tool downloads a compiler and starts a compile server in the background. After that, running an unchanged file takes under a second. The Compiling and Compiled lines appear whenever something had to be recompiled. I’ll leave them out of most of the book’s examples from here on.

There’s no class in that file. def defines a method, and @main marks this one as the program’s entry point. From that the compiler generates the class and the main(String[] args) that the JVM starts from. You can see the result under the .scala-build directory that has appeared next to your file, where there’s now a hello.class.

A method definition reads in a different order from Java’s: the name and parameters first, then a colon and the return type, then an = and the body. Unit is Scala’s equivalent of void. println needs neither an import nor System.out in front of it. It’s one of a few methods that are available everywhere.

There are no braces around the body either. As in Python, the body is whatever is indented under the def. Try putting the braces back, with a semicolon for good measure:

@main def hello(): Unit = {
  println("Hello from Scala");
}

That runs as well. Braces are still legal, and code written before Scala 3 is full of them. I use the indented style in this book, as the official Scala 3 documentation does.

1.3. The REPL

Scala has an interactive prompt, known as the REPL (read, evaluate, print, loop). Start it with scala repl. It prints a welcome line and then waits at a scala> prompt. The numbers in the list below are the seats at each of a restaurant’s six tables, which we come back to in the next section. Type these in:

scala> 2 + 3
val res0: Int = 5

scala> val seats = List(2, 2, 4, 4, 6, 8)
val seats: List[Int] = List(2, 2, 4, 4, 6, 8)

scala> seats.sum
val res1: Int = 26

scala> seats.filter(n => n >= 4)
val res2: List[Int] = List(4, 4, 6, 8)

scala> "table for two".toUpperCase
val res3: String = "TABLE FOR TWO"

scala> seats.sum / seats.size
val res4: Int = 4

scala> res1 + 1
val res5: Int = 27

scala> seats = List(10)
-- [E052] Type Error: ------------------------------------------------------------------------------
1 |seats = List(10)
  |^^^^^^^^^^^^^^^^
  |Reassignment to val seats
  |
  | longer explanation available when compiling with `-explain`
1 error found

Apart from the last one, each reply has the form val name: Type = value. When you defined seats, you never said it was a List[Int], which is how Scala writes Java’s List<Integer>. The compiler worked that out from the right-hand side. This is type inference. Java’s var does it for local variables, but Scala does it almost everywhere, so Scala code has far fewer type names in it than Java code does. It’s still statically typed, and the types the REPL prints are fixed at compile time. The session ends with a deliberate failure. seats is a val, Scala’s version of a final variable. Trying to reassign it is a compile error, complete with a position and an error code. Scala’s own var keyword is the counterpart of val: it declares a variable that can be reassigned. Types are inferred for both.

List(2, 2, 4, 4, 6, 8) builds a list, with no new and no List.of. Calls such as seats.sum and seats.size are method calls, not field accesses. Scala methods that take no arguments and simply return a value are usually declared and called without parentheses, and Java’s no-argument methods can be called that way too. By convention the parentheses stay on methods that do something, which is why hello() has them.

Most of the rest works the way it does in Java. A Scala string is a Java string, making "table for two".toUpperCase the toUpperCase() that java.lang.String has in Java. Dividing one Int by another truncates, hence the 4 from seats.sum / seats.size. Every Java library is available in the same way, your company’s internal jars and every JDBC driver included. The argument to filter is a lambda, which Scala writes with => where Java uses ->.

Results that you didn’t name get names anyway (res0, res1 and so on). The res1 + 1 line uses one. Type res2. and press Tab to see what else a List can do.

Leave the REPL with :quit or Ctrl-D. I’d keep one open in a spare terminal while you read, though. If something in this book looks wrong or surprising, type it in and see.

1.4. Something closer to real work

From here on, the code in this book belongs to one project: Fully Booked, a booking system for a single restaurant. I picked restaurant bookings because the rules need no explaining. A table can’t hold two parties at once, and a party of six doesn’t fit at a table for two.

Its first program finds a table. Given the size of a party, it picks the smallest of the restaurant’s six tables that they’ll fit at. Save it as tables.scala:

case class Table(number: Int, seats: Int)

val tables = List(
  Table(1, 2), Table(2, 2), Table(3, 4),
  Table(4, 4), Table(5, 6), Table(6, 8)
)

@main def findTable(partySize: Int): Unit =
  val bigEnough = tables.filter(table => table.seats >= partySize)
  if bigEnough.isEmpty then
    println(s"Sorry, nothing seats $partySize")
  else
    val best = bigEnough.minBy(table => table.seats)
    println(s"Table ${best.number} (seats ${best.seats})")

Arguments for your program go after a --, which separates them from arguments meant for the scala command itself:

$ scala run tables.scala -- 3
Table 3 (seats 4)
$ scala run tables.scala -- 5
Table 5 (seats 6)
$ scala run tables.scala -- 12
Sorry, nothing seats 12

Read tables.scala from the top as if it were Java, and most of it makes sense. case class Table(number: Int, seats: Int) is close to a Java record: one line declares a class with two fields, plus the constructor, equals, hashCode and toString that go with them. You create a Table without new. The list of tables is a val at the top level of the file, outside any class, with its type inferred as List[Table].

findTable is where it stops looking like Java. filter is called directly on the list, with another lambda, and hands back a new List. No .stream() goes in front and no .toList() behind. The if has a then and no parentheses. minBy picks the element for which its lambda returns the lowest value, here the table with the fewest seats. In the strings with an s in front, $partySize is replaced by the variable’s value and ${best.number} by the value of a whole expression.

minBy throws an exception on an empty list, and the only thing preventing that here is the isEmpty check above it, which would be easy to leave out. Chapter 5 has a better way to handle an answer that might be “nothing”.

Now try to misuse the program. findTable declares its parameter as partySize: Int, so the entry point that @main generates has to turn a command-line string into an integer. Leave the argument off, then pass a word where the number should be:

$ scala run tables.scala
Illegal command line: more arguments expected
$ scala run tables.scala -- abc
Illegal command line: java.lang.NumberFormatException: For input string: "abc"

1.4.1. The same program in Java

For comparison, this is how I’d write it in Java 25:

record Table(int number, int seats) {}

List<Table> tables = List.of(
    new Table(1, 2), new Table(2, 2), new Table(3, 4),
    new Table(4, 4), new Table(5, 6), new Table(6, 8));

void main(String[] args) {
    int partySize = Integer.parseInt(args[0]);
    var best = tables.stream()
        .filter(table -> table.seats() >= partySize)
        .min(Comparator.comparingInt(Table::seats));
    if (best.isEmpty()) {
        IO.println("Sorry, nothing seats " + partySize);
    } else {
        Table table = best.get();
        IO.println("Table " + table.number() + " (seats " + table.seats() + ")");
    }
}

If your JDK is version 25, java FindTable.java 3 runs it and prints the same answer. On an older JDK it won’t compile, because it relies on things that arrived in Java 25. A small program like this one no longer needs a class around its methods and fields, public static on its main, or imports for List and Comparator. IO.println is new as well.

That’s 18 lines against 14, and what’s left over is things like new, .stream(), Integer.parseInt and a Comparator. It’s clutter, but you probably stopped noticing it years ago. Java has improved a great deal since lambdas and records arrived, and I wouldn’t learn a new language to save four lines. The differences that do justify it begin in chapter 4, with collections.

1.5. Breaking it on purpose

You’re going to read a lot of Scala compiler errors, so let’s cause one. In tables.scala, change table.seats on the filter line to table.seat. Run the program again:

$ scala run tables.scala -- 3
[error] ./tables.scala:9:42
[error] value seat is not a member of Table - did you mean table.seats?
[error]   val bigEnough = tables.filter(table => table.seat >= partySize)
[error]                                          ^^^^^^^^^^
Compilation failed

Put the s back.

Scala’s compiler checks far more than javac does. Much of this book is about arranging code so that a mistake shows up like this, on your screen, where Java might have given you a NullPointerException in production.

This error was easy to read, but once generic types and library machinery get involved an error can run to a dozen lines. I’ll go through the nasty ones as we hit them.

1.6. Pinning versions

I said earlier that it doesn’t matter if your Scala version is newer than mine. Add these two lines at the very top of tables.scala:

//> using scala 3.9.0
//> using jvm 25

These are directives. The compiler sees them as comments, but the scala command reads them before it compiles anything and treats them as build settings, in this case which version of Scala to compile with and which JDK to run on. If you don’t have that compiler or that JDK, it downloads them. A file that starts with these two lines builds the same way on your laptop as it does on mine.

Libraries are declared in the same way, with //> using dep followed by the library’s Maven coordinates, in place of a pom.xml or build.gradle.

I’ve pinned 3.9 because it’s the current LTS (long-term support) release. Scala 3 has two kinds of release. Most libraries are built against an LTS version, because those get bug fixes for years. 3.9 became the LTS in September 2026. Between LTS versions come “Scala Next” releases a few times a year with newer features, 3.10 being the latest as I write. At work, use the LTS unless you need something specific from a newer release.

1.7. An editor

A plain text editor is enough for this chapter. From the next one onwards you’ll want errors shown as you type, plus the ability to hover over a name and see the type the compiler inferred for it. That means VS Code or IntelliJ.

In VS Code, install the Metals extension. Metals is Scala’s language server, the background program that an editor asks for completions, errors and types. Because it gets its errors and types from the real compiler, your editor never disagrees with your build about whether the code compiles. The same server works in Neovim, Zed, Emacs and anything else that speaks the Language Server Protocol.

If you write Java for a living you probably have IntelliJ IDEA open already, and with the Scala plugin installed you can stay there, keeping the refactoring tools and the debugger you’re used to. It also copes well with a project that mixes Java and Scala. For years its weakness was a type checker of its own, which sometimes marked valid Scala 3 code as an error, but current versions highlight Scala 3 using the compiler by default and that complaint has mostly gone away.

Whichever you pick, run scala setup-ide . in your working directory before you open that directory in the editor. The command writes a small .bsp directory that tells the editor how the code is built.

If you have no preference, use VS Code with Metals.

1.8. Two kinds of Scala codebase

When somebody says they work on a Scala codebase, they could mean one of two quite different things. The first is written as a more concise Java. You’ll find classes and traits (traits are Scala’s interfaces), a dependency injection container, exceptions for errors and Future (Scala’s counterpart to CompletableFuture) for anything asynchronous, with mutable fields wherever they’re convenient. Usually it sits on a large framework: Play if it’s a web application, Akka (or Pekko, the fork made when Akka stopped being open source) if it’s built around actors (objects that communicate only by sending each other messages) and streaming. Data pipelines written for Apache Spark, the cluster computing engine, tend to look like this too. A Java developer can usually find their way around such code quickly. A great deal of the Scala written in the 2010s is of this kind, and much of it is still running and still being hired for.

The second is written in the functional style. To change a booking, this code builds a new one with the difference applied and leaves the old one alone. A method that can fail hands the failure back to its caller as an ordinary return value, where Java would throw. The part that takes the most getting used to is how such code talks to the outside world: a database query or an HTTP call is wrapped in a type called IO and run by a library known as an effect system, of which the two big ones are Cats Effect and ZIO. It’ll probably look strange to you at first, with hardly a var in sight and method signatures like IO[Either[BookingError, Booking]].

It’s all one language and the two kinds of code can call each other, but their libraries barely overlap. Developers who prefer one kind tend to hold firm views about the other.

This book has four parts and covers both kinds, the more concise Java first. Part I is the first kind, Scala as a Java developer tends to write it at first. By the end of it you should be able to read and change code in that sort of codebase. Parts II and III work towards the functional style one piece at a time. Wherever a library supplies some clever abstraction, we write a small version of it ourselves before using the library’s. Part IV builds a complete service that way. Then the final chapter rebuilds a slice of it in Play, since that could well be what your next employer runs.

I take the book as far as the functional style because I think it’s the reason to pick Scala in the first place. If what you want is Java with less typing, Kotlin gives you that with better tooling and less to learn. Scala’s advantage over Java and Kotlin is a type system, and a set of libraries built on it, that let the compiler check things other languages leave to tests and code review, such as whether every way a request can fail has been handled. The same libraries make concurrent code much easier to get right.

1.9. The downsides

Compiling is noticeably slower than it is for Java, to the point where a large project can take minutes to build from clean. Incremental compilation hides most of that while you’re working, but CI builds are long.

You’ll also find far fewer Scala jobs than Java jobs. In the six months to November 2026, about one in two hundred adverts for IT contract work in the UK mentioned Scala.

Scala 3 arrived in 2021 with enough changes that migrating a big codebase from Scala 2 is a project in itself, one that many companies still haven’t started. Expect to meet Scala 2 in production. I teach Scala 3 only, with appendix A as a guide to reading the older language when you run into it.

Scala’s libraries also come in rival camps that don’t combine well, so a team has to pick one. Typelevel is a group of projects built around Cats Effect, among them the HTTP library http4s and the database library doobie. ZIO has its own equivalents of each. Akka and Pekko come with an HTTP server and streaming of their own. Li Haoyi has written a set of deliberately simple libraries (Cask for HTTP, uPickle for JSON, and others) that avoid effect systems altogether. This book uses Typelevel. If you end up at a ZIO company instead, most of what you learn here carries over.

1.10. Where Fully Booked goes from here

tables.scala is as small as Fully Booked gets. A real booking system has awkward cases to deal with. Two people ask at the same moment for the last table free at eight o’clock, and exactly one of them should get it. A booking that was cancelled an hour ago must not be seated.

Over the course of the book, Fully Booked grows from scripts like tables.scala into a tested HTTP service, backed by Postgres and packaged as a Docker image. The code for every chapter can be downloaded from scalafoundations.com. If you skip a chapter, the download has the code as that chapter left it.

1.11. Exercises

Solutions are in the book’s downloadable code, under ch01/exercises.

  1. Run tables.scala for a party of 2. Tables 1 and 2 both have two seats. Which one do you get, and what does that tell you about how minBy treats a tie?

  2. Add a table 7 with ten seats, and check that a party of 9 is given it.

  3. Start the REPL with scala repl tables.scala, which loads the file first so that tables is available at the prompt. Work out the total number of seats in the restaurant. Then find how many tables seat four or more. Type tables. and press Tab to see the methods a List has; map, sum and count are the ones you need. map works as it does on a Java stream, and count takes a lambda as filter does.

  4. Change the program so that it prints every table the party would fit at, smallest first, instead of only the best one. sortBy takes the same kind of lambda as minBy, and foreach runs a lambda once for each element.

  5. Give findTable a second parameter, name: String, and include the name in the output. Then run it with too few arguments.