Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 735
Lars Triers Avatar asked Sep 06 '16 10:09

Lars Triers


2 Answers

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 the case classes such as the way they can be constructed aims at facilitating/enabling their use in such statements.

like image 200
midor Avatar answered Sep 28 '22 10:09

midor


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..."

like image 23
chiastic-security Avatar answered Sep 28 '22 10:09

chiastic-security