是否需要一个类的伴随对象(单例)?为什么我要创建一个类,比如说Foo并为它创建一个伴随对象?
我正在浏览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 …Run Code Online (Sandbox Code Playgroud)