A case class is a class that may be used with the match/case
statement.
def isIdentityFun(term: Term): Boolean = term match {
case Fun(x, Var(y)) if x == y => true
case _ => false
}
You see that case
is followed by an instance of class Fun whose 2nd parameter is a Var. This is a very nice and powerful syntax, but it cannot work with instances of any class, therefore there are some restrictions for case classes. And if these restrictions are obeyed, it is possible to automatically define hashcode and equals.
The vague phrase "a recursive decomposition mechanism via pattern matching" means just "it works with case
". (Indeed, the instance followed by match
is compared to (matched against) the instance that follows case
, Scala has to decompose them both, and has to recursively decompose what they are made of.)
What case classes are useful for? The Wikipedia article about Algebraic Data Types gives two good classical examples, lists and trees. Support for algebraic data types (including knowing how to compare them) is a must for any modern functional language.
What case classes are not useful for? Some objects have state, the code like connection.setConnectTimeout(connectTimeout)
is not for case classes.
And now you can read A Tour of Scala: Case Classes