Scala:比较新鲜物体

Max*_*ime 3 compiler-construction scala compiler-warnings

我正在浏览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())
                        ^
Run Code Online (Sandbox Code Playgroud)

如果我编写一个实现==方法的类,它也会产生这个警告:

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
Run Code Online (Sandbox Code Playgroud)

编辑:谢谢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
    }
}
Run Code Online (Sandbox Code Playgroud)

oxb*_*kes 14

请注意,您永远不 应该覆盖该== 方法(您应该覆盖该equals方法).我假设通过一个对象,Scala意味着没有定义equals方法的新对象.

如果不覆盖equals,则==比较是参考比较(即使用eq),因此:

new F() == new F()
Run Code Online (Sandbox Code Playgroud)

永远都是假的.

  • 对于案例类,“equals”被覆盖。 (2认同)