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:
Syntax
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
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)
}
Login to try C/C++/Java/PHP code in the editor
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
- Comparing two case class instances with
eqand expecting equality, when==compares values buteqcompares references. - Trying to change a field like
p1.x = 5, when case class parameters arevalby default. - 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: