Scala:比较新鲜对象 [英] Scala: comparing fresh objects

查看:91
本文介绍了Scala:比较新鲜对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览scala测试,我不明白为什么在比较两个新鲜对象时编译器会产生警告。

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

这是测试的输出:
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())
                        ^

如果我写了一个实现 == 方法也将产生此警告:

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

编辑:感谢oxbow_lakes,我必须重写equals方法,而不是==

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
    }
}


推荐答案

请注意,您切勿覆盖 == 方法(您应覆盖等于方法)。我认为,通过新鲜对象,Scala意味着没有定义的等于方法的新对象

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.

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

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

new F() == new F()

始终为假。

这篇关于Scala:比较新鲜对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆