Take the 2-minute tour ×

While looking for something else, quite out of mere coincidence I stumbled upon few comments about how diabolical case class inheritance is. There was this thing called ProductN , wretches and kings, elves and wizards and how some kind of a very desirable property is lost with case classes inheritance. So what is so wrong with case class inheritance ?

share|improve this question
add comment

1 Answer

One word: equality

case classes come with a supplied implementation of equals and hashCode. The equivalence relation, known as equals works like this (i.e. must have the following properties):

  1. For all x; x equals x is true (reflexive)
  2. For x, y, z; if x equals y and y equals z then x equals z (transitive)
  3. For x, y; if x equals y then y equals x (symmetric)

As soon as you allow for equality within an inheritance hierarchy you can break 2 and 3. this is trivially demonstrated by the following example:

case class Point(x: Int, y: Int)
case class ColoredPoint(x: Int, y: Int, c: Color) extends Point(x, y) 

Then we have:

Point(0, 0) equals ColoredPoint(0, 0, RED)

But not

ColoredPoint(0, 0, RED) equals Point(0, 0)

You might argue that all class hierarchies may have this problem, and this is true. But case classes exist specifically to simplify equality from a developer's perspective (among other reasons), so having them behave non-intuitively would be the definition of an own goal!

There were other reasons as well; notably the fact that copy did not work as expected and interaction with the pattern matcher.

share|improve this answer
And what about a little elaboration :) ? –  ashy_32bit Jun 22 '12 at 15:15
It seems like such an asymmetric equivalence would be a useful thing in the OO paradigm, in the same way that at the type level a ColoredPoint is-a Point but not vice-versa. Might have to call it something other than equals though... maybe subEquals? –  Luigi Plinge Jun 22 '12 at 18:58
@LuigiPlinge perhaps canReplace, supersedes, specifies, or overrides for the reverse relationship? Anything to indicate the >=-ness (or >: if you like) of it. It seems much easier for me to name it in terms of >= rather than <=. –  Dan Burton Jun 22 '12 at 22:26
On second thoughts, such a thing would be tricky (impossible?) to implement due to the possibility of upcasting, so maybe it's not such a great idea –  Luigi Plinge Jun 22 '12 at 23:52
This example is not compilable in 2.10.2 –  ruslan Aug 3 '13 at 7:22
add comment

Your Answer


