Scala 3 · 35 of 42

Scala 3: what changed

Scala 3 shipped in 2021: the biggest revision of the language since it was created, built on a new compiler that was developed under the codename “Dotty”.

The good news: it is still very much Scala. Everything the basic tour taught you (val/var, type inference, case classes, pattern matching, higher-order functions) works exactly the same. If you’ve done the basic tour, you already know Scala 3.

What changed falls into three buckets:

  1. Cleaner syntax: braces became optional (indentation works, like Python), control structures read more like English (if x then y else z), and boilerplate like wrapper objects disappeared.
  2. New constructs: real enums, extension methods, and top-level definitions replace the old encodings (sealed trait hierarchies, implicit classes, package objects).
  3. A saner type system: implicits were redesigned into given/using, and new types arrived: union (A | B), intersection (A & B), and opaque types.

The worksheet on the left is a taste of all of it. The next pages take these one at a time.

Note: everything in this section runs on Scala 3, as does the rest of this site.
//Scala 3 in one worksheet; details in the next pages

//new control syntax: `then` and `do`, parentheses optional
val n = 42
val parity = if n % 2 == 0 then "even" else "odd"
println(parity)

//enums, finally
enum Suit:
  case Hearts, Diamonds, Clubs, Spades
println(Suit.values.mkString(", "))

//extension methods (goodbye implicit class boilerplate)
extension (s: String)
  def shout = s.toUpperCase + "!"
println("scala".shout)

//indentation can replace braces (both styles work)
def describe(suit: Suit): String =
  suit match
    case Suit.Hearts | Suit.Diamonds => "red"
    case _                           => "black"
println(describe(Suit.Spades))

//union types
def fmt(x: Int | String) = s"<<$x>>"
println(fmt(1))
println(fmt("one"))

Contents

Scala basics

  1. Overview
  2. Scalculator
  3. Operators are methods
  4. Variables
  5. Final variables
  6. Printing values
  7. String interpolation
  8. String formatting
  9. Useful operations
  10. Method definition
  11. Method definition 2
  12. Method definition 3
  13. Anonymous functions
  14. Anonymous functions 2
  15. Return multiple values
  16. Declare multiple variables
  17. Assign multiple variables
  18. Loops using while
  19. Loops using for
  20. Loops without loops
  21. If
  22. Match as a switch
  23. Arrays
  24. Lists
  25. Sets
  26. Maps
  27. Mutable collections
  28. Collections: accessing elements
  29. Collections: concatenation
  30. Mutable collection operations
  31. Immutable collections with var
  32. Collections: useful methods
  33. Classes
  34. Classes, continued

What's new in Scala 3

  1. Scala 3: what changed
  2. Optional braces & new control syntax
  3. Top-level definitions & @main
  4. Enums & ADTs
  5. Extension methods
  6. given & using
  7. Union & intersection types
  8. Smaller niceties