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

Case Class

Exercise 1: Defining and Instantiating Case Classes

case class Book(title: String, authors: List[String])

val book1 = Book("Scala Programming", List("Martin Odersky"))
val book2 = Book("Programming in Scala", List("Martin Odersky", "Lex Spoon", "Bill Venners"))
val book3 = Book("Functional Programming in Scala", List("Paul Chiusano", "Rúnar Bjarnason"))

Exercise 2: Pattern Matching on Case Classes

def describeBook(book: Book): String = book match {
  case Book(title, authors) if authors.length > 1 => s"$title, written by multiple authors."
  case Book(title, authors) => s"$title, written by ${authors.head}."
}

println(describeBook(book1)) // Output: Scala Programming, written by Martin Odersky.
println(describeBook(book2)) // Output: Programming in Scala, written by multiple authors.

Exercise 3: Copying and Modifying Case Classes

val book1Updated = book1.copy(authors = book1.authors :+ "Venners Bill")
println(book1Updated)

Exercise 4: Case Classes in Collections

val books = List(book1, book2, book3)

def titlesByAuthor(author: String, books: List[Book]): List[String] =
  books.filter(_.authors.contains(author)).map(_.title)

println(titlesByAuthor("Martin Odersky", books)) // Output: List(Scala Programming, Programming in Scala)