Scala 类和案例类 == 比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22103257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:05:21  来源:igfitidea点击:

Scala class and case class == comparison

scalaequality

提问by peter

I don't quite understand why when we compare two instance with the same properties of a class without overriding the equalsmethod that it will give a false. But it will give a truewhen we compare two instances of a case class. For example

我不太明白为什么当我们比较两个具有类的相同属性的实例而不覆盖equals它会给出false. 但是true当我们比较一个案例类的两个实例时,它会给出一个。例如

 class A(val name: String, val id: Int)
 case class B(name: String, id: Int)

 object Test {
    val a1 = new A('a',1)
    val a2 = new A('a',1)
    println(a1 == a2)   //this returns false

    var b1 = B('b',1)
    var b2 = B('b',1)
    println(b1 == b2)   //this returns true

 }

Could someone explain why, please?

有人能解释一下为什么吗?

回答by wheaties

A case classimplements the equalsmethod for you while a classdoes not. Hence, when you compare two objects implemented as a class, instead of case class, what you're comparing is the memory address of the objects.

A为您case class实现了该equals方法,而 aclass则没有。因此,当您比较两个实现为 a 的对象classcase class,您比较的是对象的内存地址。

It's really the same issues as when you have to deal with equality in Java. See this Artima blog postabout writing equalsin Java (and Scala) written by Bill Venners, Martin Odersky, and Lex Spoon.

这与您必须在 Java 中处理平等的问题实际上是相同的。请参阅由 Bill Venners、Martin Odersky 和 ​​Lex Spoon 撰写的关于用 Java(和 Scala)编写的Artima 博客文章equals