案例类继承的* so *错误是什么? [英] What is *so* wrong with case class inheritance?

查看:133
本文介绍了案例类继承的* so *错误是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在寻找别的东西时,我只是偶然发现了一些关于恶魔案件类继承的评论。有一个名为 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):


  1. 对于所有 x ; x等于x true (反身)

  2. 对于 x y z ; if x等于y y等于z 然后 x等于z (及物)

  3. 对于 x y ; if x等于y 然后 y等于x (对称)

  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)

只要在继承层次结构中允许相等就可以中断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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆