Programming Languages
Scala 3 from the basics to effect systems, type classes, build tools and the library ecosystem.
A path for developers who know another language and want to work in Scala. It covers the language itself — types, collections, pattern matching, functional error handling, laziness — then build tools, platforms, functional programming concepts and the main library families for backends, concurrency, data and UI. Each subject links the official documentation or the project's own docs.
The subjects follow the roadmap.sh Scala roadmap.
Scala is a statically typed language mixing objects with functional programming, compiling to the JVM, JavaScript (Scala.js) and native code (Scala Native). Learn Scala 3 — its cleaner syntax and redesigned implicits are where the ecosystem has moved, though plenty of production code is still on 2.13.
docs.scala-lang.org hosts the Scala 3 book, the Tour, the language reference, collection guides and the migration guide; the API docs (Scaladoc) cover the standard library type by type.
EPFL's free online courses (Functional Programming Principles in Scala and its follow-ups) are the classic structured route, taught by the language's creators. Do the exercises — reading alone does not stick.
"Programming in Scala" (Odersky et al.) is the comprehensive reference; "Functional Programming in Scala" teaches FP from first principles. Check that a book covers Scala 3 before buying.
Conference talks (Scala Days, Scalar, Functional Scala) and community channels are a good way to see libraries and idioms in action once you know the basics. Treat older talks with care: many predate Scala 3.
Install with Coursier (cs setup), which gives you scala, scala-cli, sbt and a JDK in one step. Then pick an editor: IntelliJ IDEA with the Scala plugin, or any editor talking to the Metals language server.
JetBrains' IDE plus the free Scala plugin: strong refactoring, sbt import, debugger and its own type checker (which occasionally disagrees with the compiler — trust the build). Community Edition is enough.
Install the Metals extension; it imports sbt, Mill or Scala CLI builds via BSP and gives completions, go-to-definition, worksheets and debugging using the real compiler.
Neovim with the nvim-metals plugin (or any LSP client) connects to Metals for full IDE features in the terminal.
A fast native editor; its Scala extension adds syntax highlighting and launches Metals for language features.
Use scala-ts-mode or scala-mode with lsp-mode or eglot pointing at Metals.
Sublime Text with the LSP package and LSP-metals gives Metals features inside Sublime.
val binds an immutable reference, var a reassignable one; idiomatic Scala uses val almost everywhere. Types are inferred but can be written explicitly (val n: Int = 1), and every value is an object — there are no separate primitive types at the language level.
Byte, Short, Int (32-bit, the default) and Long (suffix L), compiled to JVM primitives where possible. Overflow wraps silently; use BigInt for arbitrary size and Math.addExact to detect overflow.
Double (64-bit, default for 1.5) and Float (suffix f) follow IEEE 754, so 0.1 + 0.2 != 0.3. Use BigDecimal for money.
Scala strings are java.lang.String enriched with collection methods (map, filter, take). Interpolators s"…$x", f"$d%.2f" and raw"…", plus triple-quoted multi-line strings with stripMargin.
Boolean with true/false, short-circuit && and ||, and !. Conditions must be Boolean — no truthy numbers or strings.
The type with a single value (), returned by expressions run only for side effects (like println). A method returning Unit is a hint that it does something rather than computes something.
The bottom type: a subtype of every type with no values. throw has type Nothing, which is why if (ok) 1 else throw … still types as Int; Nil is a List[Nothing].
Types parameterised by other types, like List[A] or Map[K, V], so one implementation works for many element types with full type safety. Understanding the type hierarchy and how conversions apply tells you what the compiler will and will not accept.
Any at the top splits into AnyVal (numbers, Boolean, Unit, Char) and AnyRef (all objects); Null and Nothing sit at the bottom. With explicit nulls enabled, Null is no longer a subtype of reference types.
Declared in square brackets on classes, traits and methods: def first[A](xs: List[A]): A. Add upper (A <: Shape) or lower (B >: A) bounds to constrain them.
Numeric widening (Int to Long) happens automatically; user-defined implicit conversions are given Conversion[A, B] instances in Scala 3 and need import scala.language.implicitConversions. Use them sparingly — they hide behaviour.
Operators are ordinary methods: a + b is a.+(b), and any single-parameter method can be called infix. Precedence comes from the first character, and methods ending in : (like ::) associate to the right.
if/else is an expression that returns a value, so there is no ternary operator. Scala 3 also allows if x > 0 then … else … without braces; for more than two branches, match is usually clearer.
Scala models data with classes, traits and singleton objects, combining OO encapsulation with functional immutability. Most domain models end up as case classes and enums; plain classes are for things with identity and behaviour.
Constructor parameters go in the class header (class Account(val id: String)); val/var make them fields. Classes have reference equality unless you override equals; no new needed in Scala 3.
Interfaces that can hold concrete methods and fields, mixed into classes with extends A with B (or commas in Scala 3). Linearization decides which overridden method wins; traits can take parameters in Scala 3.
A singleton created lazily on first use — Scala's replacement for static members. A companion object shares a name and file with a class and can access its private members; it is where factories and given instances live.
The standard library offers immutable collections by default (scala.collection.immutable) and mutable ones on request, all sharing one rich API. Choose by access pattern: List for head/tail recursion, Vector for indexed access, Set/Map for lookups.
A mutable, fixed-size JVM array (Array[Int] is a real int[]) with collection methods added implicitly. Fast and interoperable with Java, but arrays compare by reference — use sameElements.
An evenly spaced integer sequence stored as start, end and step: 1 to 10, 0 until n, 10 to 0 by -2. Commonly drives for loops without allocating elements.
The general ordered-sequence trait; Seq(...) builds a List by default. Use IndexedSeq when you need fast random access, and accept Seq in APIs to stay flexible.
An immutable singly linked list: O(1) prepend with :: and pattern matching on head :: tail, but O(n) indexing and append. The workhorse for recursive algorithms.
An immutable indexed sequence backed by a wide tree, with effectively constant-time access, update, append and prepend. A good default when you index or append a lot.
Unordered unique elements with fast contains; SortedSet/TreeSet keep ordering. Calling map on a set can shrink it when results collide.
Key–value pairs built with Map("a" -> 1). get returns an Option, getOrElse provides a fallback, and updated/+/- return new maps. withDefaultValue changes apply on missing keys.
ArrayBuffer, ListBuffer, mutable.Map and friends in scala.collection.mutable. Use them locally for performance-sensitive building, then expose an immutable result.
Methods are defined with def and belong to a class or object; functions are values of type A => B that can be passed around. Scala converts methods to functions automatically (eta-expansion) when a function is expected.
Call with parentheses, named arguments (f(x = 1)) and defaults; multiple parameter lists enable currying and better type inference. Parameterless methods (list.size) are called without parentheses.
Inline functions such as x => x * 2 or the placeholder shorthand _ * 2. They close over surrounding values and are what you pass to map, filter and friends.
A total function handles every input; a PartialFunction[A, B] is defined only where its case clauses match, with isDefinedAt to check. collect and Akka message handlers rely on them.
Higher-order functions can build and return new functions, e.g. def adder(n: Int): Int => Int = _ + n. Useful for configuration, currying and composing behaviour with andThen/compose.
A small set of combinators replaces most loops: transform with map, select with filter, flatten nested results with flatMap, aggregate with folds. They return new collections and chain naturally.
Returns the first element matching a predicate as an Option — Some(x) or None — and stops as soon as it finds one.
Keeps elements satisfying a predicate; filterNot keeps the rest and partition returns both. Prefer withFilter in chains to avoid an intermediate collection.
Runs a side-effecting function on each element and returns Unit. Use it only for effects like printing; if you are building a result, you want map or a fold.
Applies a function to every element and returns a collection of the results, of the same collection type where possible. On Option, Future and Either it transforms the contained value.
Maps each element to a collection (or Option) and flattens the results into one. It is the operation for comprehensions desugar to and the core of monadic chaining.
xs.foldLeft(init)((acc, x) => …) threads an accumulator through the collection from left to right — sums, building maps, state machines. Stack-safe on List, unlike foldRight on large inputs.
collect filters and maps in one step with a partial function (case Some(x) => x); collectFirst returns the first match as an Option and stops early.
while exists but is rare; for loops iterate over anything with foreach. Most iteration is done with collection methods or recursion instead of mutating counters.
for x <- xs; y <- ys if x != y yield (x, y) desugars to flatMap, map and withFilter, so it works on any type with those methods — Option, Either, Future, effect types — not only collections.
try { … } catch { case e: IOException => … } finally { … } is an expression with a value, and the catch block is a pattern match. Catch NonFatal(e) rather than Throwable so fatal JVM errors still propagate.
Beyond interpolation, strings support split, trim, toIntOption, mkString on collections and StringBuilder for efficient building. Everything is Unicode UTF-16 underneath, as on the JVM.
Create a pattern with """\d+""".r; use findAllIn, replaceAllIn, and capture groups directly in pattern matching (case Date(y, m, d) =>). Patterns are anchored when matched in a case.
match destructures values by type, constructor, literal or extractor, with guards and bindings, and returns a value. Combined with sealed hierarchies the compiler warns when a case is missing — the core of algebraic data types in Scala.
Immutable data classes with structural equals/hashCode, a readable toString, copy for updates, and auto-generated apply/unapply so they can be built and matched without ceremony.
A sealed trait can only be extended in its own file, so the compiler knows every subtype and checks matches for exhaustiveness. The Scala 2 way of writing sum types; Scala 3 enums cover most cases.
obj(args) is sugar for obj.apply(args). Companion objects define apply as a factory, which is why you write List(1, 2) and why collections and maps can be called like functions.
Scala 3 enum defines both simple enumerations and parameterised ADTs (enum Shape { case Circle(r: Double); case Square(s: Double) }) with values, ordinal and exhaustive matching.
Singleton case values with a good toString and pattern-matching support, used for the parameterless members of a sealed hierarchy (case object Empty extends Tree). Mostly replaced by enum cases in Scala 3.
An extractor: unapply takes a value and returns an Option of its parts (or a Boolean), letting any object appear in a case pattern. Write your own to match on parsed strings or domain views.
Functional Scala models failure as values instead of throwing: absence with Option, typed errors with Either, captured exceptions with Try. They compose with map, flatMap and for comprehensions, so the happy path stays linear.
Some(value) or None — the replacement for null. Wrap nullable Java results with Option(x), then use map, getOrElse and fold rather than .get.
Left(error) or Right(value), right-biased since 2.12 so map/flatMap work on success. Use a sealed error type on the left to make failures explicit in signatures.
Try(expr) captures non-fatal exceptions as Failure(e) and results as Success(v). Handy at boundaries with throwing Java APIs; convert to Either with toEither for richer error types.
Deferring evaluation until a value is needed: avoids wasted work, makes infinite sequences possible and lets you short-circuit pipelines. The trade-off is less predictable timing and memory use.
lazy val x = expensive() computes once, on first access, and caches the result thread-safely. Good for costly initialisation; beware hidden cycles and the synchronisation cost.
A parameter typed => A is evaluated each time it is used, not at the call site. This is how getOrElse, Try(…) and custom control structures delay or skip evaluation.
Collections whose elements are computed on demand — iterators, views and LazyList. Use them to process huge or infinite data or to stop after the first few results.
Iterator yields elements one at a time and can be traversed only once — calling size consumes it. Ideal for streaming lines from a file; convert to a collection if you need to reuse it.
xs.view.map(f).filter(p) builds a lazy pipeline that runs only when forced (toList, take), avoiding intermediate collections. Re-evaluated on each traversal, so force it once.
An immutable linked list whose elements are computed lazily and memoised — LazyList.from(1) is infinite. It replaced Stream in 2.13; hold on to its head and memoised elements are kept in memory.
Controlling what code can see: block and lexical scope, access modifiers, packages and imports, and context parameters that are resolved from the surrounding scope. Members are public by default.
private limits access to the class and its companion; protected adds subclasses. Qualifiers like private[mypkg] widen access to an enclosing package.
Packages organise code and namespaces; Scala 3 allows top-level definitions without a package object. Imports can rename (import a.{B as C}), exclude and appear in any scope.
Parameters filled in by the compiler from instances in scope: using clauses and given instances in Scala 3, implicit in Scala 2. They pass context like an ExecutionContext or a type class instance.
Functional code expresses loops as functions that call themselves on smaller input. On the JVM deep recursion overflows the stack, so learn which forms the compiler optimises and how to restructure the rest.
When the recursive call is the last action, the compiler rewrites it as a loop. Annotate with @tailrec so compilation fails if it is not actually tail-recursive; use an accumulator parameter to get there.
For mutual or non-tail recursion, return a description of the next step instead of calling it, and run steps in a loop on the heap. scala.util.control.TailCalls and effect types like Cats Effect IO do this.
return in Scala is discouraged (inside lambdas it throws). Stop early instead with find, collectFirst or lazy views, or with scala.util.boundary and break in Scala 3.3+.
Build tools compile, test, package and manage dependencies. Scala CLI is ideal for scripts and small projects, sbt is the long-standing default for libraries and services, and Mill is a simpler alternative; JVM tools Gradle and Maven also work.
The official scala command runner: compile, run, test and package single files or small projects with //> using dep … directives — no build file required. Also exports to sbt or Mill when a project grows.
The standard Scala build tool: build.sbt in a Scala DSL, incremental compilation via Zinc, a continuous ~test mode and a large plugin ecosystem. Powerful, with a learning curve around scopes and tasks.
A build tool where builds are plain Scala objects with cached, parallel tasks. Easier to read and extend than sbt for many teams.
Its built-in Scala plugin compiles Scala with Zinc; a reasonable choice in mixed Java/Kotlin/Scala organisations already standardised on Gradle.
Builds Scala via the scala-maven-plugin. Common in enterprise Java shops; fewer Scala-specific conveniences than sbt or Mill.
Scala libraries cluster into ecosystems with different philosophies: Typelevel (Cats, Cats Effect), ZIO, Akka/Pekko actors, and Li Haoyi's simple direct-style libraries. Pick one family per project — mixing their effect types adds friction.
Typelevel's library of functional abstractions — Functor, Monad, Traverse, Semigroup — plus data types like Validated and NonEmptyList. Foundation of http4s, Doobie, FS2 and Circe.
A family of pragmatic, easy-to-read libraries: os-lib for files and processes, uPickle for JSON, Requests-Scala, Cask for HTTP, Scalatags, plus the Mill build tool and Ammonite. Ideal for scripts and simple services.
Actor-based toolkits for concurrent and distributed systems. Akka moved to the BSL licence in 2022; Apache Pekko is the Apache-licensed fork from Akka 2.6 with the same APIs under org.apache.pekko.
You can also use standalone libraries and the standard library — Future, Java libraries, small focused tools — without committing to a framework family. Fine for small apps and scripts.
The same Scala code can target several runtimes. The JVM is the default and best supported; Scala.js and Scala Native reuse your skills in the browser and as native binaries, but only libraries published for that platform work there.
Scala compiles to JVM bytecode and calls Java libraries directly. You get mature GC, JIT, profilers and the whole Java ecosystem; JDK 17 or 21 LTS are safe choices.
An LLVM-based ahead-of-time compiler producing native executables with fast startup and C interop. Library support is smaller than on the JVM.
Compiles Scala to JavaScript for browsers and Node.js, with type-safe facades for JS libraries and shared code between client and server.
Compiles a JVM application ahead of time into a standalone binary with millisecond startup — useful for CLIs and serverless. Reflection-heavy code needs configuration.
An expression is referentially transparent if you can replace it with its value without changing the program. This is what makes code easy to reason about, refactor and test, and it is the property effect systems are built to preserve.
Functions whose output depends only on their input and which have no side effects — no I/O, mutation or exceptions. Keep business logic pure and push effects to the edges.
A monad is a type with pure (wrap a value) and flatMap (sequence a computation that depends on the previous result) obeying a few laws. Option, Either, List, Future and IO are all monads, which is why for comprehensions work on each.
The branch of mathematics that names patterns like functors, monoids and monads. You do not need it to use Cats or ZIO, but it explains why the laws matter.
A direction in Scala 3 for tracking effects through context parameters: a function that needs to do I/O or throw asks for a capability value in a using clause. It keeps a direct style of code while making effects visible in types.
An experimental Scala 3 feature that tracks which capabilities a value captures (A^{io}) so they cannot escape their scope — for example, a file handle leaking out of withFile. Still evolving.
Ad-hoc polymorphism: define behaviour (Show, Ordering, Encoder) separately from data and supply instances with given. Lets you add capabilities to types you do not own, and is the backbone of Cats, Circe and many libraries.
Scala's type system is unusually expressive: variance, bounds, union and intersection types, opaque types, match types and higher-kinded types. Use the power to make illegal states unrepresentable, not to show off.
List[+A] is covariant (a List[Cat] is a List[Animal]), Function1[-A, +B] is contravariant in its input. Variance annotations are checked, which is why mutable containers must be invariant.
def sort[A: Ordering](xs: List[A]) is shorthand for requiring a given Ordering[A]. The concise way to ask for type class instances.
Code that runs at compile time to generate or inspect code. Scala 3 replaced the experimental Scala 2 macros with inline, quotes and splices, and a TASTy reflection API; library authors use them for derivation and zero-cost abstractions.
Scala has several mature test frameworks that plug into sbt, Mill and Scala CLI. Pick one per project — MUnit for simplicity, ScalaTest for flexibility, ZIO Test for ZIO code — and add property-based testing with ScalaCheck for logic-heavy code.
The most widely used framework, with many styles (AnyFunSuite, AnyFlatSpec, AnyWordSpec), rich matchers and support for async and integration tests.
A lightweight framework with JUnit-like test("…") blocks, clear diffs on failure and support for JVM, Scala.js and Native. A good default for new projects.
Li Haoyi's minimal framework with a small API and fast startup, used across the com-lihaoyi libraries.
Java's standard framework works from Scala, handy in mixed Java/Scala codebases and existing CI setups.
Tests are ZIO effects, with test aspects, a controllable test clock and built-in property-based testing. The natural choice for ZIO code.
A specification-style framework for writing executable, readable specifications with matchers and data tables.
A load-testing tool with a Scala (also Java/Kotlin) DSL for HTTP and other protocols, producing detailed HTML reports. Use it for performance testing against a running service.
Scala has HTTP libraries for every style: Play for full-stack MVC, Pekko/Akka HTTP for actor systems, http4s for pure FP, and Tapir to describe endpoints once and derive servers, clients and OpenAPI docs.
SoftwareMill's HTTP client with one API over many backends (sync, Future, Cats Effect, ZIO). Requests are immutable descriptions you send with a chosen backend.
A small Sinatra-style framework on the Servlet API. Simple to start with, but less active than the alternatives today.
A full-stack web framework with routing, templates, JSON, forms and hot reload, built on Pekko in recent versions. Good for traditional web apps and REST APIs.
Define endpoints as typed values, then interpret them as servers (http4s, Pekko HTTP, Netty, ZIO HTTP), sttp clients or OpenAPI documentation.
A streaming HTTP server and client built on Akka actors and streams, with a routing DSL. New projects usually choose the Pekko HTTP fork for licensing reasons.
A purely functional HTTP library on Cats Effect and FS2: routes are functions from Request to F[Response], easy to test and compose.
Effect systems represent side effects as lazy values (IO, ZIO) that are run by a runtime with lightweight fibers, safe resource handling, cancellation and structured concurrency. They keep effectful code referentially transparent.
Typelevel's IO monad and type classes, with fibers, Resource for safe acquisition and release, and a work-stealing runtime. Powers http4s, Doobie and FS2.
An effect type ZIO[R, E, A] with a typed error channel and built-in dependency injection through layers, plus its own ecosystem for HTTP, streams, config and testing.
Scala reaches the UI through Scala.js for the web, JavaFX/ScalaFX on the desktop and a few routes onto Android. Web is by far the most active of the three.
A Scala.js UI library with reactive streams (Airstream) and no virtual DOM: elements bind directly to observable values. Simple and fast for single-page apps.
A Scala.js UI library built on Cats Effect and FS2, so components are resources and state is managed with signals in a purely functional style.
Write React components in Scala.js with an API close to React's own, including hooks and JSX-like syntax.
Scala.js can drive React through facades such as Slinky or scalajs-react, giving typed props and state while reusing the React component ecosystem.
A Scala DSL over JavaFX that makes scene graphs, bindings and properties read like declarative Scala.
The Java desktop UI toolkit (OpenJFX), usable directly from Scala. Distributed separately from the JDK since Java 11.
A Gradle plugin that adds Scala compilation to the Android build so activities and logic can be written in Scala alongside Java or Kotlin.
Another route compiles a JavaFX app with GraalVM Native Image through Gluon's tooling into an Android package. Niche, and expect rough edges.
Options range from the standard library Future, to effect systems with fibers, to direct-style libraries built on JVM virtual threads, and streaming libraries for back-pressured data flows.
SoftwareMill's direct-style concurrency on Java 21 virtual threads: structured scopes with supervised, par, channels and flows — no monadic wrappers.
An experimental EPFL library exploring direct-style, structured async in Scala 3 using capabilities, across JVM and Native.
Functional streams for Scala on Cats Effect: compositional, resource-safe, back-pressured streams for files, sockets and queues. The streaming layer under http4s and Doobie.
A toolkit using algebraic effects tracked in the type (A < (IO & Abort[E])), aiming for the power of ZIO or Cats Effect with more flexible effect composition.
Reactive Streams implementation with Source, Flow and Sink graphs, back-pressure and integrations (Alpakka/Pekko Connectors) for Kafka, files and databases.
ZIO's pull-based streams (ZStream, ZPipeline, ZSink) with typed errors and resource safety, integrating with the rest of ZIO.
Scala has a strong history in distributed systems and big data: Spark is written in it, and actor toolkits handle clustering, sharding and persistence for stateful services.
A distributed engine for batch and streaming data with DataFrame, Dataset and SQL APIs. Check which Scala version your Spark release supports — it often lags behind.
Lightbend's actor toolkit with cluster sharding, persistence and distributed data. Commercially licensed (BSL) since 2.7; check the licence terms before adopting.
Apache's open-source fork of Akka 2.6: typed actors, cluster, sharding, persistence and streams under the Apache 2.0 licence.
Talking to databases and serialising data. Scala's database libraries trade off between type-safe SQL as strings, compile-time query generation and collection-like DSLs; JSON libraries derive codecs from case classes.
A purely functional JDBC layer on Cats Effect: write SQL with the sql"…" interpolator, map results to case classes and compose queries as ConnectionIO values.
A straightforward, synchronous SQL library with interpolated queries and an optional query DSL. Easy to learn and keeps you close to SQL.
Compile-time generated SQL from Scala collection-like queries, so query errors show up when compiling. Maintained as part of the ZIO ecosystem.
Functional relational mapping: queries look like operations on Scala collections and compile to SQL, run asynchronously with Future.
Play's JSON library with Reads, Writes and Format and macros like Json.format[User]. Usable outside Play.
The Typelevel JSON library: automatic or semi-automatic codec derivation, cursors for navigating documents, and integration with http4s.
jsoniter-scala generates codecs at compile time and is among the fastest JSON libraries on the JVM, with low allocation. Pick it when serialisation is hot.
Li Haoyi's simple JSON and binary (MessagePack) serialiser: write(value) and read[T](json) with derives ReadWriter.
Game development is a niche in Scala but has a few working options: a pure functional engine, an ASCII engine, and the Java libGDX framework used from Scala.
A functional 2D game engine for Scala.js: game logic is pure functions from state and events to new state and scene, which makes it easy to test.
A 2D engine for ASCII-art games that run in a terminal, written in Scala 3.
libGDX is a mature cross-platform Java game framework; Scala code can call it directly and build with sbt or Gradle.
Libraries that use macros and type-level programming to remove boilerplate: deriving type class instances, transforming between similar data types, updating nested immutable data, and analysing source code.
An optics library — lenses, prisms, optionals — for reading and updating deeply nested immutable data without chains of copy.
Macro-based transformations between similar case classes (DTO to domain model) with into[Target].transform, reporting missing fields at compile time.
The classic generic programming library for Scala 2: HLists, Generic representations and type-level computation. Much of it is built into Scala 3 through Mirror and tuples.
A simple, fast library for automatic type class derivation for case classes and sealed traits, used by many codec libraries.
A library for parsing and analysing Scala source code; it powers Scalafmt, Scalafix and the Metals language server.