案例类继承有什么问题? [英] What is *so* wrong with case class inheritance?
问题描述
在寻找其他东西时,完全出于巧合,我偶然发现了一些关于案例类继承是多么邪恶的评论.有一个叫做 ProductN
的东西,可怜的和国王的,精灵和巫师的,以及某种非常理想的属性是如何随着案例类继承而丢失的.那么案例类继承有什么问题?
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
类提供了 equals
和 hashCode
的实现.被称为 equals
的等价关系的工作原理如下(即必须具有以下属性):
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
;如果x 等于 y
并且y 等于 z
那么x 等于 z
(传递) - 对于
x
,y
;如果x 等于 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.
这篇关于案例类继承有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!