Scala: comparing fresh objects

老子叫甜甜 提交于 2019-12-22 10:57:40

问题


I was browsing scala tests and I don't understand why the compiler produces a warning when you compare "two fresh objects".

This is the test' outputs: http://lampsvn.epfl.ch/trac/scala/browser/scala/trunk/test/files/neg/checksensible.check

Example:

checksensible.scala:12: warning: comparing a fresh object using `!=' will always yield true
println(new Exception() != new Exception())
                        ^

If I write a class implementing an == method it will also produces this warning:

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

EDIT: Thanks oxbow_lakes, I must override the equals method, not the ==

class Foo(val bar: Int) {
    override def equals(other: Any) : Boolean = other match { 
        case other: Foo => this.bar == other.bar
        case _ => false
    }
}

回答1:


Note that you should never override the == method (you should override the equals method instead). I assume that by a fresh object, Scala means a new object without a defined equals method.

If you do not override equals, the == comparison is a reference comparison (i.e. using eq) and hence:

new F() == new F()

will always be false.



来源:https://stackoverflow.com/questions/1536473/scala-comparing-fresh-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!