Cheat Sheet for Scala 3 Pattern Matching Constructs
()
I took most of the examples from the Scala 3 book
Some examples I adapted from the Scala Cookbook or from »the internet«
val y = 3
def pattern(x: Matchable): String = x match
// constant patterns
case 0 => "zero"
case true => "true"
case "hello" => "you said 'hello'"
case Nil => "an empty List"
// sequence patterns
case List(0, _, _) => "a 3-element list with 0 as the first element"
case List(1, _*) => "list, starts with 1, has any number of elements"
case Vector(1, _*) => "vector, starts w/ 1, has any number of elements"
case Nil => "abc"
case x :: xs => s"$x"
case x :: Nil => s"$x"
// tuple patterns
case (a, b) => s"got $a and $b"
case (a, b, c) => s"got $a, $b, and $c"
// constructor patterns
case Person(first, "Alexander") => s"Alexander, first name = $first"
case Dog("Zeus") => "found a dog named Zeus"
// type test patterns
case s: String => s"got a string: $s"
case i: Int => s"got an int: $i"
case f: Float => s"got a float: $f"
case a: Array[Int] => s"array of int: ${a.mkString(",")}"
case as: Array[String] => s"string array: ${as.mkString(",")}"
case d: Dog => s"dog: ${d.name}"
case list: List[?] => s"got a List: $list"
case list: List[X] => s"got a List: $list"
case m: Map[?, ?] => m.toString
case m: Map[A, B] => m.toString
case _: String => s"got a string"
// variable patterns
case y => s"$y"
case _ => "Unknown" // the default wildcard pattern
// Variable-binding patterns (Seite 109)
case x @ List(1, _*) => s"$x"
case x @ Some(_) => s"$x"
case p @ Person(first, "Doe") => s"$p"
// the contents of variable y (defined at the top)
case `y` => s"$y"
