我正在浏览 scala 测试,但我不明白为什么当您比较“两个新对象”时编译器会产生警告。
这是测试的输出: http: //lampsvn.epfl.ch/trac/scala/browser/scala/trunk/test/files/neg/checksensible.check
例子:
checksensible.scala:12: warning: comparing a fresh object using `!=' will always yield true
println(new Exception() != new Exception())
^
如果我编写一个实现==
方法的类,它也会产生这个警告:
class Foo(val bar: Int) {
def ==(other: Foo) : Boolean = this.bar == other.bar
}
new Foo(1) == new Foo(1)
warning: comparing a fresh object using `==' will always yield false
编辑:谢谢 oxbow_lakes,我必须重写 equals 方法,而不是 ==
class Foo(val bar: Int) {
override def equals(other: Any) : Boolean = other match {
case other: Foo => this.bar == other.bar
case _ => false
}
}