0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

Union and Intersection Types

New type features.

New Type Features

Scala 3 adds union types (A | B) and intersection types (A & B) to the type system. They let you describe values more precisely without inheritance hierarchies.

object Main:
  def main(args: Array[String]): Unit =
    println("Union: A | B, Intersection: A & B")

Union Types Basics

A union type A | B represents a value that is either an A or a B. It is a set-theoretic OR over types.

object Main:
  def show(x: Int | String): String = x match
    case i: Int    => s"int $i"
    case s: String => s"str $s"

  def main(args: Array[String]): Unit =
    println(show(42))
    println(show("hi"))

All lessons in this course

  1. Significant Indentation
  2. Enums in Scala 3
  3. Opaque Types
  4. Union and Intersection Types
← Back to Scala for Backend Engineering & Functional Programming