`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 enum
s or comparable values such as int
s or string
s 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 the case classes such as the way they can be constructed aims at facilitating/enabling their use in such statements.
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..."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With