diff --git a/src/main/scala/ed/39368.worksheet.sc b/src/main/scala/ed/39368.worksheet.sc new file mode 100644 index 0000000000000000000000000000000000000000..83bfddfc85a17634c86733008299cdbba68d30e2 --- /dev/null +++ b/src/main/scala/ed/39368.worksheet.sc @@ -0,0 +1,22 @@ +// 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) + +// 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) => s"$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 => s"${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) => s"${p.name} is ${a} years old"