From 963c3cdfdba678d5c9358834610eed2894d30e5b Mon Sep 17 00:00:00 2001 From: Matt Bovel <matthieu@bovel.net> Date: Fri, 26 May 2023 16:25:26 +0200 Subject: [PATCH] Use a Scala file instead of worksheet --- src/main/scala/ed/39368.scala | 24 ++++++++++++++++++++++++ src/main/scala/ed/39368.worksheet.sc | 22 ---------------------- 2 files changed, 24 insertions(+), 22 deletions(-) create mode 100644 src/main/scala/ed/39368.scala delete mode 100644 src/main/scala/ed/39368.worksheet.sc diff --git a/src/main/scala/ed/39368.scala b/src/main/scala/ed/39368.scala new file mode 100644 index 0000000..870538f --- /dev/null +++ b/src/main/scala/ed/39368.scala @@ -0,0 +1,24 @@ +// 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") diff --git a/src/main/scala/ed/39368.worksheet.sc b/src/main/scala/ed/39368.worksheet.sc deleted file mode 100644 index 83bfddf..0000000 --- a/src/main/scala/ed/39368.worksheet.sc +++ /dev/null @@ -1,22 +0,0 @@ -// 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" -- GitLab