Skip to content

Instantly share code, notes, and snippets.

@utenma
Created May 12, 2023 16:01
Show Gist options
  • Save utenma/27bfba6b592abd30cfdd05b549dbd916 to your computer and use it in GitHub Desktop.
Save utenma/27bfba6b592abd30cfdd05b549dbd916 to your computer and use it in GitHub Desktop.
Scala 3 Pattern Matching on Unions
type Primitive = Boolean | Int | Float | Double | Long | String
val x: Int = 1
// x: Int = 1
val y: String = "i"
// y: String = i
val z: Double = 1.0
// z: Double = 1.0
def primitiveMatch(x: Primitive) =
x match
case b: Boolean => println("Boolean")
case b: (Int | Float | Double | Long) => println("Numeric")
case b: String => println("String")
primitiveMatch(x)
// Numeric
primitiveMatch(y)
// String
primitiveMatch(z)
// Numeric
case class A()
case class B(val x: Int)
case class C()
val a: A = A()
// a: A = A()
val bOrC: (B | C) = B(2)
// bOrC: B | C = B(2)
def classMatch(x: (A | B | C)) =
x match
case a: A => println("A")
case B(_) | C() => println("B or C")
classMatch(a)
// A
classMatch(bOrC)
// B or C
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment