Scala Reference
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. The reference material consulted while preparing these pages is listed in the section bibliography. |
Welcome to the Scala reference. Scala is a statically typed language that fuses
object-oriented and functional programming on the Java Virtual Machine, and also targets JavaScript through Scala.js and
native code through Scala Native. It combines a concise, indentation-friendly syntax and strong type inference with
traits, case classes and enums, pattern matching, immutable collections, higher-order functions and a type system that
includes union, intersection, opaque and match types. Scala 3 redesigned the Scala 2 implicits into intent-based
constructs (given, using, extension methods and context bounds), added metaprogramming through inline, quotes and
splices, and ships a single scala command, Scala CLI, that runs, tests and packages programs without a build file.
History
Scala was designed by Martin Odersky and his group at the Programming Methods Laboratory (LAMP) of EPFL in Lausanne, with a first public release in 2003 and the major redesign Scala 2.0 in 2006. The research compiler Dotty, started at EPFL, became Scala 3.0 in 2021; the Scala Center at EPFL, VirtusLab and other companies take part in its development and the Scala Improvement Process (SIP) governs language changes. Since Scala 3.1.0 (21 October 2021) the language has evolved in minor releases with a long-term support (LTS) line next to the latest "Scala Next" line. Every release with its date and what changed is listed in Release History & What’s New; how the process works, and which features are experimental or in preview, is explained in Language Evolution: SIPs, Preview & Experimental.
Release baseline
This section documents Scala 3.10 (3.10.0, the current Scala Next release, announced on 12 October 2026; JDK 17 or newer
since Scala 3.8), checked on 2026-10-16. Every page also states what differs on the 3.9 LTS line (3.9.0, announced on
3 September 2026), which the official download page advises for publishing libraries. Features newer than the 3.3 LTS
(3.3.8) are marked with the release that introduced or stabilised them, for example named tuples (stable in 3.7), the
new given syntax (3.6), into (stable in 3.9) and the removal of A with B types (an error in 3.10). Features that the
official documentation labels experimental or preview are labelled as such: Scala 3.10 introduces the preview
label, which is reached with the -preview compiler flag (for instance SIP-74, partial function literals with
parentheses, which is a preview feature in 3.10). Scala 2.13 appears only as "the Scala 2 form" in comparisons and on the
migration pages. Frameworks and libraries built on Scala, such as Typelevel, ZIO, Apache Pekko, Akka, Play, Apache Spark
and Ox, are not documented here; they are listed with a brief description and links on
Ecosystem. The exception is the official Scala
Toolkit (MUnit, OS-Lib, uPickle, sttp and Cask), which belongs to the official documentation and has its own pages. The
tools used throughout are Scala CLI 1.18.0 (its 1.17.1 release is the one bundled with the 3.10.0 distribution and used for
the examples), sbt 2.0.10 and Toolkit 0.9.2.
The trailhead scenario
The examples share one small, original domain: trailhead, a toolkit that plans hikes on a network of mountain trails. It
suits Scala’s strengths — domain modelling with algebraic data types, type-safe APIs, collection pipelines, type classes
and JSON and HTTP through the Toolkit — and grows page by page: a Trail case class, a Difficulty enum, a Segment
hierarchy, opaque Km, Metres and Minutes types, a Route processed with collection pipelines, Show, Codec and
Ordering type classes, a Planner that validates with Either and Option, a WeatherService served by a local Cask
server and called with sttp, a small route DSL, an inline check of a grade literal and tests with MUnit and ScalaCheck.
A page whose concept fits the scenario poorly uses a minimal standalone example instead. Every example on
these pages was run with Scala 3.10.0 on JDK 26, or with the version named on the page, and the output shown is the real
output of that run (examples that could not be run are labelled "not run here" on their page).
How the books were used
Three books were consulted as references for concept coverage and structure: Dean Wampler’s Programming Scala (third
edition, O’Reilly, 2021), which describes Scala 3.0, Slava Schmidt’s Learn Scala Programming (Packt, 2018), which is
written for Scala 2.13 milestones, and Mads Hartmann and Ruslan Shevchenko’s Professional Scala (Packt, 2018), which is
written for Scala 2.12. None of them is the source of any example: every example is written against the current official
Scala 3.10 documentation, the official documentation wins wherever they differ, and no text, code listing or figure is
copied from a book. Each page states in prose where the books are outdated for the concepts it touches (implicits instead of
givens, extends App, A with B, Stream, the Scala 2 macros and Akka actors before Pekko, among others), and
Release History & What’s New and
Incompatibilities & Dropped Features collect
the legacy-to-modern replacements.
New here? Read in this order
-
Getting Started & Versions — what Scala is and the release lines.
-
Installing Scala — install Scala and run it.
-
Hello World & @main Methods — your first program.
-
Scala for Java, Python & JavaScript Developers — what changes if you know another language.
-
Values, Variables & Literals —
val,varand literals. -
Strings & Interpolation — string literals and interpolators.
-
Methods & Parameters — methods and their parameters.
-
Optional Braces & Indentation — the indentation-based syntax.
-
Conditionals & Loops —
if,whileand the expression-oriented style. -
Pattern Matching — the
matchexpression. -
Classes & Constructors — classes and their constructors.
-
Case Classes — immutable data with generated members.
-
Enums — simple enums and algebraic data types.
-
Traits & Mixins — reusable behaviour.
-
Collections Overview — the collections hierarchy.
-
Collection Operations —
map,filter, folds and the rest. -
Option & Null Safety — replacing
null. -
Givens & Using Clauses — the Scala 3 contextual abstractions.
-
Extension Methods — adding methods to existing types.
-
Type Classes — the type class pattern.
-
Scala CLI — run, test and package without a build file.
-
Testing with MUnit — testing with the Scala Toolkit.
The other pages can be read in any order as you need them. Coming from Scala 2 or from an older book? Start with Scala 2 & Scala 3 Compatibility and Migrating from Scala 2.
What’s covered
Getting started
-
Getting Started & Versions — What Scala is used for, its high-level features, why Scala 3, the Scala Next and LTS release lines (3.3 LTS, 3.9 LTS, 3.10), the JDK 17 floor since Scala 3.8.
-
Installing Scala — the Coursier cs setup installer, what it puts on your PATH, choosing a JDK (17, 21 or 25), Homebrew, SDKMAN!, the .deb and .rpm packages new in 3.10, nightly builds.
-
Hello World & @main Methods — the @main annotation, running it with scala run, scalac and java, command-line arguments, typed @main parameters, FromString for user-defined types, argument errors.
-
REPL, Worksheets & Scastie — the
scala replcommand and its commands, worksheets in Metals and IntelliJ IDEA, and Scastie in the browser. -
Scala for Java, Python & JavaScript Developers — a side-by-side map from Java, Python and JavaScript covering variables, strings, classes, traits, control structures, collections, functions, null handling, concurrency and tooling, plus the surprises for newcomers.
-
IDEs & Tools — the IDEs, editors and command-line tools commonly used for Scala, with links to the official pages.
Syntax and fundamentals
-
Values, Variables & Literals — val versus var, type annotations and inference, the value types Byte to Double, Char, Boolean and Unit, BigInt and BigDecimal.
-
Type Hierarchy & Matchable — Any, Matchable, AnyVal, AnyRef, Nothing, Null and Unit — casting with asInstanceOf and isInstanceOf, why Matchable exists (opaque types and parametricity).
-
Strings & Interpolation — String and StringOps, multiline strings and stripMargin, the s, f and raw interpolators, the dollar and quote escapes, the \s escape of Scala 3.10.
-
Methods & Parameters — def and return types, default and named arguments, by-name and repeated parameters, vararg splices, nested methods, symbolic operators, precedence and associativity.
-
Optional Braces & Indentation — the indentation rules and warnings, where an indentation region can start, the colon for template bodies, the quiet control syntax with then and do.
-
Packages, Imports & Top-Level Definitions — Scala 3 packages, nested and chained package clauses, import selectors (wildcard, rename, hide), import precedence, default imports, given imports.
-
Tuples & Named Tuples — tuple types and construction, element access, the Tuple operations, arities beyond 22, pattern matching and parameter untupling.
Control structures
-
Conditionals & Loops — if/then/else as an expression, the Unit result of an if without else, end markers, the quiet syntax for if and while, while loops.
-
For Comprehensions — generators, guards, value definitions, yield, how the compiler rewrites a for into foreach, map, flatMap and withFilter, what a type needs to support for.
-
Pattern Matching — match expressions, constant, variable, typed, constructor, tuple, sequence and wildcard patterns, guards, alternatives, @ binders, stable identifiers and backquotes.
-
Extractors & Pattern Bindings — unapply and unapplySeq, Boolean, single, product and name-based fixed-arity extractors, variadic extractors, extractors with using clauses, regular-expression patterns.
-
Exceptions, boundary & Early Exit — try/catch/finally as expressions, catch with patterns and guards, throw and Nothing, no checked exceptions and @throws, NonFatal, scala.util.Using.
Object orientation and domain modeling
-
Classes & Constructors — class parameters versus fields, the primary and auxiliary constructors, default parameters, val and var parameters, creator applications without new, getters.
-
Objects & Companions — singleton object, companion classes and objects, private access between companions, apply factories and creator applications, utility modules, case objects.
-
Traits & Mixins — abstract and concrete members, extends with commas and with, mixing in at instantiation, linearization and super, stackable modifications, trait parameters.
-
Inheritance: Abstract, Sealed, Open & Final — abstract classes and members, override, final, sealed in the same file, the open modifier and the adhocExtensions feature warning, planning a class for extension.
-
Case Classes — the members the compiler generates (apply, unapply, copy, equals, hashCode, toString, Product, Serializable and the Mirror), case objects, immutability and its limits.
-
Enums — simple and parameterized enum cases, fields and methods, companion objects, values, valueOf, fromOrdinal and ordinal, enums with non-singleton cases, restrictions.
-
Algebraic Data Types & GADTs — sum and product types, enum and sealed trait ADTs, exhaustivity checking, constructor proxies and widened types, variance of enum cases, recursive ADTs.
-
Composition, Export & Self Types — export clauses (selectors, renaming, exclusion, givens, exports inside extensions), self types, abstract type members, and OOP and FP style modules, with real compiler output.
-
Annotations & Visibility — Scala 3 standard annotations (@tailrec, @deprecated, @throws, @targetName, @threadUnsafe, @publicInBinary, @unchecked, @nowarn, @experimental).
Functional programming
-
Functional Programming Principles — immutability with val and case class copy, immutable collections and structural sharing, pure functions and side effects, referential transparency and the substitution model.
-
Functions as Values — function literals, underscore placeholders and their scope, function types and the FunctionN traits, andThen, compose, tupled and curried, methods versus functions.
-
Higher-Order Functions & Closures — methods that take and return functions, writing map and filter by hand, closures over val and var, the loop-capture pitfall.
-
Partial Functions — the PartialFunction trait, case-clause literals, isDefinedAt, apply and MatchError, applyOrElse, lift and unlift, collect and collectFirst, orElse, andThen.
-
Currying & Parameter Lists — partial application and eta-expansion, curried function values with curried and uncurried, type inference that flows from one parameter list to the next.
-
Recursion & Tail Calls — recursion over lists and enums, the JVM stack limit, accumulators and the @tailrec annotation with its real compiler errors.
-
Laziness — lazy val semantics, initialisation order, exceptions in initialisers, thread safety and the VarHandle implementation (Scala 3.8), the @threadUnsafe annotation.
The type system
-
Type Inference — what the compiler infers for values, methods and type arguments, how the expected type reaches lambda parameters, how branches are joined into union types.
-
Generics & Bounds — generic classes, traits and methods, explicit and inferred type arguments, upper bounds, lower bounds, combined, F-bounded, intersection and union bounds, context bounds.
-
Variance — invariance, covariance and contravariance declared once on the type, producers versus consumers, the variance of function types, and why mutable collections are invariant.
-
Union & Intersection Types — values and members of each, inference and widening of unions, transparent traits, matching on a union, erasure and overloading, unions versus enums.
-
Opaque Types & Value Classes — giving a primitive a distinct type with no runtime cost, the transparency scope of an opaque alias, companion APIs and extension methods, bounds, top-level opaque types.
-
Structural Types, Selectable & Dynamic — structural refinements, calling a member that the type only describes,
reflectiveSelectableand its reflection cost, and writing your ownSelectableorDynamic. -
Dependent & Polymorphic Function Types — inner classes tied to an instance, a result type that depends on a parameter, polymorphic function values, context-function results, and the limits of type projection.
-
Type Lambdas & Higher Kinds — type constructors with
F[_], kinds and kind checking, type lambdas, partial application of type constructors,AnyKindand kind polymorphism, and migrating from the kind-projector plugin. -
Match Types — type-level match, reduction against provably disjoint cases, stuck match types, recursive and bounded match types, termination and the recursion limit.
Contextual abstractions
-
Contextual Abstractions Overview — given, using, given imports, extension methods, Conversion, context bounds and context functions — with a Scala 2 to Scala 3 mapping table, the 3.6 syntax change.
-
Givens & Using Clauses — named, anonymous, alias, conditional and by-name givens in the 3.6 syntax and the legacy with form, generated names, using clauses, explicit using arguments, summon.
-
Context Bounds & Deferred Givens — the T: Ord shorthand and its desugaring to a using clause, named bounds with as (3.6), aggregate bounds with braces (3.6), bounds on type members.
-
Extension Methods — the extension syntax and its translation to a plain method, operators and unary operators, right-associative extensions, generic and collective extensions, using clauses.
-
Type Classes — the trait, givens and extension methods pattern, Show, Ordering, Semigroup and Monoid, Functor and Monad, laws, retroactive instances and the expression problem.
-
Type Class Derivation — the
derivesclause and the given it generates, the compiler-providedMirror, and writing a derived method withinline. -
Multiversal Equality — universal == and its pitfalls, the CanEqual type class, the strictEquality language import, deriving and defining CanEqual instances, the predefined instances.
-
Context Functions — the context function arrow, type aliases such as
Logged[T], how the compiler expands them, the builder pattern for nested DSLs and postconditions with opaque types. -
Conversions, into & Implicit Resolution —
Conversion, theimplicitConversionslanguage import and feature warnings,intoas a type constructor and as a modifier (SIP-71, stable in 3.9), and where the compiler looks for a given.
Collections
-
Collections Overview — the immutable default and the mutable package, the
Iterable,Seq,SetandMaphierarchy, the default imports and thescala.collection.immutablealiases, and howSeq,SetandMapresolve. -
Sequences — the immutable List and Vector, mutable ArrayBuffer and ListBuffer, Array, ArraySeq and IArray, Range, immutable Queue, mutable Queue and ArrayDeque, StringBuilder.
-
Sets & Maps — immutable Set and Map and their small specialised classes, mutable sets and maps, get, getOrElse, updated, updatedWith, getOrElseUpdate and default values.
-
Collection Operations — map, flatMap, filter, collect, folds and reductions, groupBy, groupMap and groupMapReduce, partition, zip, take, drop and slice, sliding and grouped, sortBy, distinctBy.
-
Views, Iterators & LazyList — strict versus non-strict operations, views and forcing, iterators and their single-use laziness, BufferedIterator, LazyList and its memoisation (replacing Stream).
-
Collection Performance & Equality — how to read the 2.13 performance-characteristics tables (C, eC, aC, Log, L), what effectively and amortized constant time mean for List, Vector, ArrayBuffer, Queue, HashSet.
-
Collections Architecture & Custom Collections — the template traits IterableOps, MapOps, SortedSetOps and SortedMapOps and their element, type-constructor and collection-type parameters.
Error handling
-
Option & Null Safety — replacing null, extracting and transforming values, Option in for comprehensions, Option as a collection of zero or one element, bridging Java nulls and java.util.Optional.
-
Either & Try — right-biased Either with Left and Right, Try with Success and Failure, for comprehensions over both, conversions between Option, Either and Try, NonFatal, Using.
Concurrency
-
Futures & Promises — ExecutionContext (global, fixed pools, virtual threads, parasitic), creating futures, callbacks, map/flatMap/for-comprehensions and the sequential-versus-parallel trap.
-
Parallel Collections & Concurrency Libraries — parallel collections with
.par, side effects and non-associative operations, task support and performance, and a pointer to the effect and actor libraries.
Metaprogramming
-
Metaprogramming Overview — the layers inline, compile-time operations, macros, reflection and staging, where each runs in the compiler, what TASTy stores, what happened to Scala 2 macros.
-
Inline — inline values, inline methods, inline parameters, inline if and inline match, transparent inline, overriding rules, the -Xmax-inlines recursion limit.
-
Compile-Time Operations — constValue, constValueOpt, constValueTuple, erasedValue, error, requireConst, codeOf, summonInline, summonFrom, summonAll.
-
Macros: Quotes & Splices — Expr and Type, quotes and splices and their staging levels, the inline definition plus macro implementation split.
-
Quoted Pattern Matching — matching
Exprvalues against quote patterns, splice patterns that bind sub-expressions, and type variables in quoted patterns (SIP-53). -
Reflection with quotes.reflect — Expr versus Term, TypeRepr, Symbol and Flags, navigating the API, positions, building trees with newVal and ValDef, Implicits.search, report.
-
Staging & TASTy Inspection — runtime staging with
scala.quoted.stagingto generate and compile specialised code while the program runs, and the TASTy Inspector.
Tooling
-
Scala CLI — run, compile, test, package, doc, fmt and repl, using directives for the Scala version, dependencies, the Toolkit and compiler options, scripts and shebangs.
-
sbt & Build Tools —
build.sbt, the directory layout, cross-versioned dependencies, common tasks, multi-project builds, cross-building and what changed in sbt 2.0. -
IDEs — Visual Studio Code with Metals, the other Metals editors (Vim, Sublime Text, Emacs, Helix), IntelliJ IDEA with the Scala plugin.
-
Compiler Options, Linting & Errors — -deprecation, -feature, -Wunused, -Wvalue-discard, -Wnonunit-statement, -Wshadow, -Wsafe-init, -Wall, -Werror and -Wconf, @nowarn, -explain and the E001 to E234 error codes.
-
Scaladoc — doc comments and tags, Markdown and wiki syntax, definition links, member groups, static documentation sites, blogs.
-
Scala.js & Scala Native — Scala.js 1.22 (JavaScript and the stable WebAssembly backend, DOM, interop and semantic differences) and Scala Native 0.5.12 (native binaries, C interop and build modes).
-
Versions, Compatibility & JDKs — Scala 3 Next and LTS release lines, source compatibility and
-source, binary and TASTy compatibility with a consumer matrix, MiMa and TASTy-MiMa for library authors, and@unroll(SIP-61, preview in 3.10).
Java interoperability
-
Using Java from Scala — Java collections with CollectionConverters, Optional with OptionConverters, streams with StreamConverters, Java classes, enums.
-
Calling Scala from Java — how Scala classes, traits, objects, companions, top-level definitions, enums, case classes, collections, Option, functions.
Testing and the Scala Toolkit
-
Testing with MUnit — getting the test dependency in Scala CLI, sbt and Mill, writing FunSuite suites, assertEquals, assert, clue, assertNoDiff, compileErrors, intercept, running all tests.
-
MUnit Async, Fixtures & Other Frameworks — asynchronous tests that return a Future, test timeouts, value transforms for other result types, FunFixture and its map2 composition, asynchronous.
-
Property-Based Testing — properties versus examples, forAll, Gen and Arbitrary generators, shrinking of counterexamples, seeds, test parameters, implication, classification.
-
Files & Processes with OS-Lib — os.Path and relative paths, reading, writing, appending, listing and walking directories, copying, moving and removing.
-
JSON with uPickle — uJson parsing, navigation, modification and construction, read and write with ReadWriter derivation (derives), the JSON shapes of case classes, enums, sealed traits, Option.
-
HTTP Client with sttp — quickRequest, headers and authentication, the uri interpolator and query parameters, request bodies, JSON with uPickle, file uploads and multipart bodies, backends.
-
Web Servers with Cask — routes and static files, path segments, query parameters, HTML with Scalatags, form and JSON input and output, websockets, cookies and decorators.
Migration
-
Scala 2 & Scala 3 Compatibility — the Scala 3 unpickler for 2.13 libraries, the 2.13 TASTy reader and why it stops at Scala 3.7, supported and unsupported features, for3Use2_13 and for2_13Use3.
-
Migrating from Scala 2 — prerequisites (macro libraries, compiler plugins, scala-reflect), the -Xsource:3 migration warnings and -quickfix on 2.13.
-
Incompatibilities & Dropped Features — every Scala 2.13 incompatibility and dropped feature with its real diagnostic, replacement and rewrite, and the 3.4 to 3.10 deprecation timeline.
-
Upgrading Between Scala 3 Versions — the recommended upgrade order, the ordered
-source:3.x-migration -rewriterecipe,-source:3.3as a fallback, and the 3.8 and 3.10 changes.
Practice and reference
-
Style Guide — indentation, naming conventions, types, nested blocks, declarations, control structures, method invocation, files and Scaladoc.
-
Domain Specific Languages — infix methods and the infix modifier, extension methods, operator precedence, by-name parameters, context function builders, custom string interpolators.
-
Language Evolution: SIPs, Preview & Experimental — the SIP process and its stages, the completed SIP list mapped to the pages that use each feature, the experimental to preview to stable lifecycle.
-
Release History & What’s New — Scala release history from 2.13.0 to 3.10.0 with an official release-notes link for every row, what changed in each release and a run-here probe.
Ecosystem and cheat sheet
-
Ecosystem — a map of the libraries, frameworks and learning resources built on or around Scala, each with a brief description and links, and the books, courses and glossary.
-
Cheat Sheet (PDF) — a one-page, printable summary of the whole section, with a Scala 2 to Scala 3 strip.
Bibliography
The reference material consulted while preparing this section. The official Scala documentation is the primary source for
every page; the books are consulted references for concept coverage only, and the third-party projects are cited only on the
ecosystem and testing pages. On any discrepancy, the official documentation wins. No text, code listing or figure is
copied from any book or documentation page. Each page lists the subset it derives from under its own == References
heading.
Official Scala documentation
-
The Scala 3 Book and every Book page cited on the pages of this section.
-
The Scala 3 Reference and every Reference page cited, including the syntax summary and the error-code pages.
-
The Tour of Scala.
-
Getting started: Install Scala and the IDE, sbt and IntelliJ pages of that guide.
-
The Scala Toolkit documentation.
-
The Guides & Overviews: collections for 2.13, the collections architecture, Futures, parallel collections, value classes, binary compatibility, JDK compatibility, compiler options, the REPL, Scaladoc, and the legacy reflection and macros guides.
-
The Scala 3 migration guide and the Scala 3 macros guide, with the TASTy overview.
-
Scaladoc and the Scala style guide.
-
The Scala Improvement Process, with each SIP cited by number where a page uses it.
-
Further reading: the official cheatsheet (Scala 2 flavoured; this section’s cheat sheet is written from scratch), the glossary, the books page and the online courses page.
-
The API reference (and the 3.9.0 and 3.3.8 versions where pages compare them).
-
Downloads and release notes: Download, All available versions, the 3.10, 3.9, 3.8, 3.7.0 and 3.6.2 announcements under news, and the 3.0 to 3.5, LTS plan, sbt 2 and Scala 2 maintenance posts under blog.
-
Source code: scala/scala3.
Specifications and standards (each is cited where a page uses it)
-
The Scala Language Specification 2.13 and the work-in-progress Scala 3 specification.
-
The Java Virtual Machine Specification and The Java Language Specification at docs.oracle.com/javase/specs for interoperability and erasure.
-
The JDK Enhancement Proposals JEP 395 (records) and JEP 444 (virtual threads).
-
IEEE 754 (floating-point arithmetic), RFC 8259 (JSON), RFC 9110 (HTTP semantics), RFC 6455 (WebSocket) and the Unicode standard.
Official tools and Toolkit libraries
Books
-
Dean Wampler, Programming Scala, third edition, O’Reilly Media, 2021. ISBN 978-1-492-07789-3. Written for Scala 3.0; consulted for concept coverage only.
-
Slava Schmidt, Learn Scala Programming, Packt Publishing, 2018. ISBN 978-1-78883-630-2. Written for Scala 2.13 milestones (pre-release); consulted for concept coverage only.
-
Mads Hartmann and Ruslan Shevchenko, Professional Scala, Packt Publishing, 2018. ISBN 978-1-78953-383-5. Written for Scala 2.12; consulted for concept coverage only.
Third-party projects (cited only on the ecosystem and testing pages; none is documented further)
-
Typelevel, ZIO, Apache Pekko, Akka, Play, Apache Spark and Ox.
-
Testing and tools: ScalaTest, ScalaCheck, Scalafmt, Scalafix, Mill and the IntelliJ Scala plugin.