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

Case Classes

A case class is a class with helpful extras added for free, like a toy that arrives with batteries and a manual. It prints nicely, compares by contents, and is easy to create without new.

In this page:

  1. Case Classes
Syntax
scala
case class ClassName(field1: Type, field2: Type)

val instance = ClassName(value1, value2)
val copy = instance.copy(field1 = new_value)

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)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Comparing two case class instances with eq and expecting equality, when == compares values but eq compares references.
  2. Trying to change a field like p1.x = 5, when case class parameters are val by default.
  3. Inheriting from one case class with another case class, which is not allowed and is discouraged.
🔒

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.