Created
May 12, 2023 16:01
-
-
Save elsaulio/27bfba6b592abd30cfdd05b549dbd916 to your computer and use it in GitHub Desktop.
Scala 3 Pattern Matching on Unions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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