案例类继承有什么问题? [英] What is *so* wrong with case class inheritance?

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

问题描述

在寻找其他东西时,完全出于巧合,我偶然发现了一些关于案例类继承是多么邪恶的评论.有一个叫做 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 类提供了 equalshashCode 的实现.被称为 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):

  1. 对于所有xx 等于 xtrue(自反)
  2. 对于xyz;如果 x 等于 y 并且 y 等于 z 那么 x 等于 z(传递)
  3. 对于xy;如果 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.

这篇关于案例类继承有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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