What is a Case Class in Scala?
Instruction: Define a case class in Scala and explain its primary uses and advantages.
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
-
easy
-
easy
-
easy
-
easy
-
easy
-
easy