Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Pattern Matching

Solutions

Exercise 1: Basic Case Class and Pattern Matching

case class Person(name: String, age: Int)

def greet(person: Person): String =
  person match
    case Person(_, age) if age < 18 => "Hello, young one!"
    case Person(name, _) => s"Hello, $name!"

// Test your function
val child = Person("Tim", 10)
val adult = Person("John", 30)

println(greet(child))  // Output: Hello, young one!
println(greet(adult))  // Output: Hello, John!

Exercise 2: Using Case Classes in Collections

def minors(people: List[Person]): List[String] =
  people.collect { case Person(name, age) if age < 18 => name }

// Test your function
val people = List(Person("Alice", 17), Person("Bob", 20), Person("Charlie", 15))
println(minors(people))  // Output: List(Alice, Charlie)