Skip to content
Snippets Groups Projects
Commit d84371c3 authored by Matt Bovel's avatar Matt Bovel
Browse files

Create 39368.worksheet.sc

parent 74514251
No related branches found
No related tags found
No related merge requests found
// 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"
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment