Skip to content
Snippets Groups Projects
39368.scala 1.09 KiB
Newer Older
// To demonstrate different ways of pattern matching, let's consider the
// following example case class and instance:
case class Person(name: String, age: Int)
val ada = Person("Ada", 36)

// Run using `sbt "runMain ed.patternMatching"`.
@main def patternMatching =
    // There are several ways to pattern match on the `ada` instance:
    // 1. Pattern matching on the case class constructor using `Person(name, age)`.
    //    If the pattern matches, the value of `n` is bound `ada.name` field, and
    //    `a` is bound to the `ada.age` field.
    ada match
        case Person(n, a) => println(f"$n is $a years old")

    // 2. We can also check only that `ada` is of type `Person` without binding its
    //    fields by using a `:` pattern. The `:` pattern is used to check if a value is
    //    of a certain type.
    ada match
        case p: Person => println(f"${p.name} is ${p.age} years old")

    // 3. If we want to both bind the fields and bind a value to the whole instance,
    //    we can use an `@` pattern.
    ada match
        case p @ Person(n, a) => println(f"${p.name} is ${a} years old")