Lars Triers Lars Triers - 1 month ago 4x
Scala Question

Why case class is named 'case'?

`Case is 'an instance of a particular situation; an example of something occurring'.

So my question is - why Scala 'case' classes are named as 'case'? What is the point? Why it is 'case', not 'data' class or something else? What does mean 'case' in that.. case :)


The primary use of the case keyword in other languages is in switch-statements which are mostly used on enums or comparable values such as ints or strings being used to represent different well-defined cases:

switch (value)
   case 1: // do x -
   case 2: // do y - 
   default: // optional

In scala these classes often represent the specific well-defined possible instances of an abstract class and are used in much the same way imperative code uses switch-statements within match-clauses:

value match {
    case Expr(lhs, rhs) => // do x
    case Atomic(a) => // do y
    case _ => // optional, but will throw exception if something cannot be match whereas switch won't

Much of the behavior of the case classes such as the way they can be constructed aims at facilitating/enabling their use in such statements.