Lars Triers
Lars Triers

Reputation: 167

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 :)

Upvotes: 10

Views: 372

Answers (2)

midor
midor

Reputation: 5557

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 matched whereas switch won't
}

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

Upvotes: 9

chiastic-security
chiastic-security

Reputation: 20520

It's because they can be used for pattern matching. A case in English usage means one of the possibilities; and that's what pattern matching works out for you.

e.g., "There are three cases we must consider here..."

Upvotes: 1

Related Questions