Scala: comparing fresh objects

I was looking at scala tests and I don’t understand why the compiler generates a warning when you compare “two fresh objects”.

These are the test results: 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 that implements a method ==, it also throws 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 have to override the equals method, not ==

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

, == ( equals). , Scala equals.

equals, == (.. eq) , ,

new F() == new F()

.

+13

Source: https://habr.com/ru/post/1719594/


All Articles