== 对于 Scala 中的 class 和 "non-case" class

== for case class and "non-case" class in Scala

我正在研究Scala,运行进入下面的谜题。

我可以定义如下情况classes:

abstract class Expr
case class Number(n: Int) extends Expr

当我从 class Number 创建两个实例并比较它们时

val x1 = Number(1)
val x2 = Number(1)
x1 == x2

我得到以下结果:

x1: Number = Number(1)

x2: Number = Number(1)

res0: Boolean = true

所以x1x2是一样的。

但是,如果我在 Number class 定义中删除 case 修饰符,即

abstract class Expr
class Number(n: Int) extends Expr

然后以相同的方式比较 Number class 中的两个实例

val x1 = new Number(1)
val x2 = new Number(1)
x1 == x2

我有以下输出:

x1: Number = Number@1175e2db

x2: Number = Number@61064425

res0: Boolean = false

说的是这次x1x2不一样

你能告诉我这是为什么吗? case 比较两个实例有什么区别?

谢谢, 潘

当您在 Scala 中定义 case class 时,编译器会生成一个 equals 方法来检查深度相等性(即 class 的内容)。

发件人:http://www.scala-lang.org/old/node/107

For every case class the Scala compiler generates equals method which implements structural equality and a toString method.

当您删除 case 关键字时,您会生成常规 classes,并对它们执行 == 检查引用(浅)相等性。由于您正在比较 class 的两个唯一实例,即使它们的内容相同,它们也无法引用相等性。

浅层平等与深层平等的区别见:
What is the difference between being shallowly and deeply equal? How is this applied to caching?