Why Scala?
Most programming languages pick a side. Java, C# and C++ grew up around objects: bundles of data with methods attached, organised into classes and interfaces. Haskell, OCaml and the Lisps grew up around functions: small pieces of computation that take values and return new values, combined like building blocks. Each camp has good ideas the other lacks. Objects are excellent at organising large programs into modules with clear boundaries; functions are excellent at expressing data transformations without hidden state.
Scala's bet is that you do not have to choose. In Scala every value is an object, including numbers and functions, and every function is a value you can store in a variable, pass to another function or return as a result. Classes, traits (a richer kind of interface) and inheritance sit next to immutable data, pattern matching and higher-order functions, and the language is designed so the two styles strengthen each other instead of fighting.
The name is short for scalable language. The idea is that the same language should feel right for a ten-line script and for a system with a million lines and a hundred engineers. Small programs stay small because the compiler infers most types and the syntax has little ceremony. Large programs stay manageable because the type system is strong: it can describe precisely what a piece of code accepts and returns, and the compiler checks those descriptions everywhere.
Scala also made a practical choice: it compiles to bytecode for the Java Virtual Machine (JVM). A Scala program can use any Java library directly, runs on the same mature, fast runtime as Java, and can be deployed anywhere Java runs. That decision is a big part of why companies were willing to adopt it.
In this course you will learn to write Scala the way experienced teams write it today: mostly immutable values, small functions, data modelled with case classes and enums, errors as values, and the compiler as a helpful colleague.
Where Scala came from
Scala was designed by Martin Odersky, a professor at EPFL (the Swiss Federal Institute of Technology in Lausanne). Before Scala, Odersky had worked on adding generics to Java: his GJ compiler became the basis of the standard javac compiler, and the generics that arrived in Java 5 owe a great deal to that work. He wanted a language that kept the JVM's practicality but took functional programming seriously. Design began at EPFL in 2001, and the first public release came in early 2004. Scala 2.0 followed in 2006.
In the following years Scala found its first large users. Twitter moved parts of its back end to Scala; LinkedIn used it in several systems, and Apache Kafka was first written there in Scala and Java. In 2009 researchers at UC Berkeley started Apache Spark in Scala, and Spark became one of the most widely used engines for processing large datasets. The company Typesafe (later renamed Lightbend) was founded in 2011 to support Scala commercially, together with the Akka actor toolkit and the Play web framework. In 2016 EPFL founded the Scala Center, a non-profit that looks after the language's open-source tools, documentation and education.
Meanwhile Odersky's group worked on a new theoretical foundation for the language, a calculus called DOT (dependent object types), and on a research compiler built on it, nicknamed Dotty. Dotty became Scala 3, released in May 2021. Scala 3 kept the core of the language but cleaned up its rough edges: a quieter syntax with optional braces, real enums, a clearer replacement for Scala 2's implicit keyword (given and using, which you will meet in lesson 6), union and intersection types, and opaque type aliases. Scala 3 can use libraries compiled for Scala 2.13, so the move did not split the ecosystem.
Since Scala 3.5 (2024), the scala command you type at a terminal is Scala CLI, a tool that compiles and runs single files and small projects without any build configuration. The Scala team also designates certain releases as long-term support (LTS) lines, starting with 3.3, for teams that want to stay on one version for years; the website says which LTS is current. This course was checked with Scala 3.10 and uses Scala 3 syntax throughout.
The toolchain
Getting Scala onto your machine means getting a few cooperating pieces.
Definition— JDK
The Java Development Kit contains the Java Virtual Machine, which actually runs compiled Scala code, and Java's standard library, which Scala programs can call. Recent Scala 3 releases need a modern JDK; this course was run on JDK 21, a long-term-support release. The official Scala installer can download one for you.
Definition— The scala command (Scala CLI)
scala compiles and runs Scala source files. scala run hello.scala (or simply scala hello.scala) compiles the file and runs its @main method; scala alone starts the REPL (read–eval–print loop), where you type expressions and see their values immediately. It can also run tests (scala test), format code (scala fmt) and package programs. Settings live in comments at the top of a file called using directives, for example //> using scala 3.10.1 to pin the Scala version or //> using dep ... to add a library.
Definition— sbt
sbt is the long-established build tool for multi-module Scala projects: it manages dependencies, incremental compilation, tests and publishing, configured in a build.sbt file. Most open-source libraries and many company code bases use it. You will meet it, and its alternative Mill, in lesson 8; for single files and small projects, Scala CLI is simpler.
Definition— Scastie
Scastie is the official online playground at scastie.scala-lang.org. It compiles and runs Scala in the browser and lets you share a link to your code. Every complete program in this course runs there.
The recommended installation is on scala-lang.org/download. It uses a small installer called Coursier (cs setup), which fetches a JDK if you need one, the scala command, sbt and the formatter. Package managers such as Homebrew and SDKMAN also carry Scala. Afterwards, check what you have:
scala version # the Scala CLI and default Scala versions
java -version # the JDK that will run your programs
scala # start the REPL; type :quit to leaveFor writing code, most Scala developers use either Visual Studio Code or another editor with Metals, the Scala language server, or IntelliJ IDEA with its Scala plugin. Both underline errors as you type and show the types the compiler inferred, which is very helpful while learning.
Your first programs
Hello, world
Save this as hello.scala and run scala run hello.scala:
@main def hello(): Unit =
println("Hello, world!")
println("Sawubona, mhlaba! Bonjour, le monde! 你好,世界!")Hello, world!
Sawubona, mhlaba! Bonjour, le monde! 你好,世界!Line by line:
def hello(): Unitdefines a method calledhellowith no parameters.Unitis its result type: it returns nothing interesting (Scala'sUnitplays the role ofvoidin Java and C).@mainis an annotation marking this method as the program's entry point. Any top-level method can be the entry point; its name does not have to bemain.- The
=says "the body follows". In Scala 3 the body can be an indented block, as here, with no braces. The same program in the brace style, which Scala 2 required and Scala 3 still accepts, looks like this:
@main def hello(): Unit = {
println("Hello, world!")
}printlnprints a value followed by a newline. Strings are written in double quotes and may contain any Unicode text.- There are no semicolons. Scala infers the end of a statement from line breaks.
Both styles are common in real code. Many teams that started on Scala 2 still use braces; new Scala 3 code mostly uses indentation, and that is the style of this course. A formatter (lesson 8) can convert between them.
Arguments from the command line
A @main method can take parameters, and Scala parses the command-line arguments into them. String* means "any number of strings":
@main def greet(names: String*): Unit =
if names.isEmpty then
println("Hello, whoever you are!")
else
for name <- names do
println(s"Hello, $name!")Run with no arguments, it prints:
Hello, whoever you are!Arguments for your program come after --, which separates them from options meant for the scala command. Running scala run greet.scala -- Amara Kenji Sofía prints:
Hello, Amara!
Hello, Kenji!
Hello, Sofía!Notice if ... then ... else, the for ... do loop and s"Hello, $name!", which inserts the value of name into the string. All three get a proper treatment in the next lesson.
Building strings
Scala has three built-in string interpolators, written as a letter just before the opening quote:
@main def interpolation(): Unit =
val language = "Scala"
val year = 2004
val ratio = 2.0 / 3.0
println(s"$language first appeared in $year.")
println(s"Scala 3 arrived ${2021 - year} years later.")
println(f"two thirds is about $ratio%.3f")
println(f"[$language%8s] [$language%-8s]")
println(f"$year%07d")
println(raw"In a raw string, \n is two characters.")
println("""Triple quotes let a string
|run over several lines.""".stripMargin)Scala first appeared in 2004.
Scala 3 arrived 17 years later.
two thirds is about 0.667
[ Scala] [Scala ]
0002004
In a raw string, \n is two characters.
Triple quotes let a string
run over several lines.valintroduces a named value that cannot be reassigned. You will usevalfar more than its reassignable cousinvar.- The
sinterpolator replaces$namewith the value ofname, and${...}with the value of any expression. - The
finterpolator does the same but lets you add a printf-style format after each value:%.3frounds to three decimals,%8sright-aligns in eight characters (%-8sleft-aligns),%07dpads an integer with zeros. Unlike C'sprintf, the compiler checks that each format matches its value's type:$language%dwould not compile. - The
rawinterpolator leaves backslashes alone, which is handy for regular expressions and Windows paths. - Triple-quoted strings can span lines and contain quotes without escaping.
stripMarginremoves everything up to and including a|at the start of each line, so you can indent the text along with your code.
A program that computes something
Here is a function and a loop together. Read it for its shape; functions get their own lesson:
def isLeap(year: Int): Boolean =
(year % 4 == 0 && year % 100 != 0) || year % 400 == 0
@main def leapYears(): Unit =
val years = List(1900, 2000, 2023, 2024, 2100)
for y <- years do
val kind = if isLeap(y) then "a leap year" else "a common year"
println(s"$y is $kind")
val count = years.count(isLeap)
println(s"$count of ${years.size} are leap years")1900 is a common year
2000 is a leap year
2023 is a common year
2024 is a leap year
2100 is a common year
2 of 5 are leap yearsThree things here are typical Scala:
isLeapis defined at the top level of the file, outside any class. Scala 3 allows that; Scala 2 required everything to live inside anobject.if isLeap(y) then "a leap year" else "a common year"is an expression with a value, stored inkind. There is no separate "ternary operator" becauseifalready returns a value.years.count(isLeap)passes the functionisLeapto the list'scountmethod, which calls it on each element and counts thetrueresults. Passing functions to methods is the bread and butter of Scala, and lesson 5 is full of it.
What happens when you run a Scala program
Scala is compiled ahead of time, like Java. When you type scala run hello.scala, Scala CLI hands the file to the Scala compiler, which checks types and produces JVM bytecode in .class files, along with .tasty files. TASTy (typed abstract syntax trees) is Scala 3's record of the fully type-checked program; tools and later compilers read it, and it is what lets Scala 3 code and Scala 2.13 libraries work together. Scala CLI caches the results, so running the same unchanged file a second time skips compilation.
Then the JVM starts and runs the bytecode. The JVM begins by interpreting it and, as the program runs, its just-in-time (JIT) compiler turns the busiest methods into optimised machine code. That gives Scala programs two characteristic traits: they start more slowly than a C or Go program (the JVM needs a moment to warm up), and long-running ones, such as servers and data jobs, become very fast. If start-up time matters, Scala Native compiles to a native executable, and GraalVM's native-image can do the same for JVM programs.
The compiler is your most important teacher, so it is worth learning to read it. Suppose you misspell a name inside an interpolated string:
@main def oops(): Unit =
val greeting = "Salaam"
val count: Int = greeting.length
println(s"$greting, Yusuf! ($count letters)")The compiler refuses to build it (the path is shortened here):
-- [E006] Not Found Error: main.scala:4:13
4 | println(s"$greting, Yusuf! ($count letters)")
| ^^^^^^^
| Not found: greting - did you mean greeting?
|
| longer explanation available when compiling with `-explain`
1 error found
Compilation failedIt gives an error code (E006), the file, line and column, underlines the exact span, and suggests a fix. Notice that the mistake inside the string was caught before the program ran: interpolators are checked at compile time. Type errors look similar. Writing val year: Int = "2004" produces:
-- [E007] Type Mismatch Error: main.scala:2:18
2 | val year: Int = "2004"
| ^^^^^^
| Found: ("2004" : String)
| Required: Int"Found" is what you wrote, "Required" is what the context needs. Reading those two lines carefully solves most type errors. When a message is not clear enough, the -explain option asks the compiler for a longer explanation with examples: with Scala CLI, scala run --scalac-option -explain hello.scala.
Note
Read the first error first. One mistake, such as a missing parenthesis, can confuse the compiler about everything after it; fixing the first error often makes the rest disappear.
Common misconceptions
Misconception
"Scala is Java with shorter syntax." It runs on the same virtual machine and can call Java code, but the languages think differently. Scala treats functions as values, prefers immutable data, has pattern matching, enums with data, type classes, and a type system that can express things Java's cannot. You can write Java-like Scala, but you would miss most of what the language offers.
Misconception
"You need to know category theory to use Scala." Some popular Scala libraries borrow vocabulary from abstract mathematics, and you will see words like monad in discussions. You do not need any of it to write good Scala. This course explains the few ideas that matter in plain terms, when they come up.
Misconception
"Scala 3 code must use indentation, and braces are gone." Braces are still fully supported, and you can mix the styles across files. What Scala 3 changed is that braces became optional. Most teams pick one style and let the formatter enforce it.
Misconception
"Scala is slow because it runs on the JVM." The JVM's JIT compiler produces fast machine code for long-running programs, and many high-throughput systems run on it. What is slow is start-up and the first moments before the JIT warms up, which matters for short command-line tools, not for servers or data pipelines.
Exercises
Try anything you are unsure of in Scastie or with scala run, then check your reasoning against the worked solutions.
1. Getting started with Scala
Warm-upHumanYou have a single file, report.scala, with a @main method and no build configuration. Which command compiles and runs it?
2. Getting started with Scala
Warm-upHumanWhat does the Scala 3 compiler produce from your source code when targeting the JVM?
3. Getting started with Scala
CoreComputationalWhat does this program print? Write the two lines separated by a single space.
@main def ex(): Unit =
val n = 7
println(s"$n:${n * n}")
println(f"${10.0 / 4}%.1f|${42}%5d|")
4. Getting started with Scala
CoreComputationalHow many lines does this program print?
@main def ex(): Unit =
print("a")
print("b")
println()
println("c\nd")
println(raw"e\nf")
5. Getting started with Scala
CoreComputationalWhat does this program print?
@main def ex(): Unit =
val year = 2026
val parity = if year % 2 == 0 then "even" else "odd"
println(s"$year is $parity, ${year % 100} past the century")
6. Getting started with Scala
CoreHumanWhat does @main in @main def greet(names: String*): Unit do?
7. Getting started with Scala
StretchHumanWhich statements are true? Choose all that apply.
Further reading and resources
- Download ScalaThe official installation instructions for Linux, macOS and Windows.
- Scala 3 Book: A Taste of ScalaThe official book's quick tour of the language.
- Scala CLI documentationEvery command of the tool behind
scala, including using directives. - Scala 3 Book: String Interpolation
- ScastieRun any program from this lesson in your browser.