案例类继承的* so *错误是什么? [英] What is *so* wrong with case class inheritance?
问题描述
在寻找别的东西时,我只是偶然发现了一些关于恶魔案件类继承的评论。有一个名为 ProductN
的东西,wretches和国王,精灵和向导,以及如何通过case类继承丢失某种非常理想的属性。那么case case继承有什么问题呢?
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 ?
推荐答案
一个词:平等
case
类提供的实现等于
和的hashCode
。等价关系,称为等于
就像这样(即必须具有以下属性):
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):
- 对于所有
x
;x等于x
是true
(反身) - 对于
x
,y
,z
; ifx等于y
和y等于z
然后x等于z
(及物) - 对于
x
,y
; ifx等于y
然后y等于x
(对称)
- For all
x
;x equals x
istrue
(reflexive) - For
x
,y
,z
; ifx equals y
andy equals z
thenx equals z
(transitive) - For
x
,y
; ifx equals y
theny equals x
(symmetric)
只要在继承层次结构中允许相等就可以中断2和3.这可以通过以下示例轻松证明:
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)
然后我们有:
Point(0, 0) equals ColoredPoint(0, 0, RED)
但不
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!
还有其他原因;值得注意的是, copy
未按预期工作和与模式匹配器的互动。
There were other reasons as well; notably the fact that copy
did not work as expected and interaction with the pattern matcher.
这篇关于案例类继承的* so *错误是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!