← Back to Scala Course | Chapter 7: OOP Basics | Lesson 6 of 7

Case Classes

In this page:

  1. Case Classes

Case Classes

A case class automatically generates useful boilerplate: a companion object with apply, value-based equals/hashCode, a readable toString, and support for pattern matching. Case class fields are val by default, making instances immutable unless you explicitly mark a field var. Case classes are the idiomatic Scala way to model simple data-holding types.

Note: Case classes get pattern-matching support and value equality for free, making them the default choice for simple data models in Scala.

Example: Case Classes

markup
case class Point(x: Int, y: Int)

object Main extends App {
  val p1 = Point(1, 2)
  val p2 = Point(1, 2)

  println(p1)
  println(p1 == p2) // value equality, not reference equality

  val p3 = p1.copy(y = 99)
  println(p3)
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.