What is a Case Class in Scala?

Instruction: Define a case class in Scala and explain its primary uses and advantages.

Context: This question tests the candidate's knowledge of Scala's case classes, which are a fundamental construct for modeling immutable data and pattern matching. It checks for an understanding of how case classes facilitate concise code, automatic generation of boilerplate code like getters, toString, and copy methods, and their role in pattern matching.

Updated

A case class is a class intended for data modeling, with generated support for construction, pattern matching, structural equality, hashing, a readable representation and copying. Parameters in the first parameter list are public val fields unless declared otherwise. Case classes

final case class Person(name: String, age: Int)
@main def caseClassExample(): Unit = {
  val ava = Person("Ava", 25)
  val older = ava.copy(age = 26)
  assert(ava == Person("Ava", 25))
  assert(ava.age == 25 && older.age == 26)
  val label = older match {
    case Person(name, age) => s"$name is $age"
  }
  assert(label == "Ava is 26")
}

copy creates another instance and keeps unspecified fields; it is a shallow copy. A case class can declare a var, and even a val field can reference a mutable object. Therefore case classes are not automatically deeply immutable or thread-safe. Mutable equality-relevant fields can also make an instance unsafe as a hash-map key after insertion.

Use case classes for records, messages and alternatives in a sealed data model. Validate domain constraints separately: Person("", -1) still constructs successfully here. The ability to omit new is not unique to case classes in Scala 3, which also provides universal apply syntax for ordinary classes.

Related Questions