views:

177

answers:

1

Hi,

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
    }
}
+10  A: 

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.

oxbow_lakes
This is apparently not true for case classes, where Scala performs extensional equality check by default. E.G. "case class F() ; println(new F() == new F())"
John Clements
For case classes `equals` _is_ overridden.
Alexey Romanov