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
- Significant Indentation
- Enums in Scala 3
- Opaque Types
- Union and Intersection Types