我正在使用Scala处理一些简单的数据结构和集合,但我注意到了一些奇怪的行为。以下是对象:
class State (protected val trackmap: Map[Int, List[String]]) {
override def clone : State = {
new State(Map() ++ trackmap)
}
override def toString = { "State: " + trackmap.toString }
def equals (other: State) : Boolean = {
//println("Comparing " + trackmap + " to " + other.trackmap)
trackmap == other.trackmap
}
def == (other: State) : Boolean = {
this equals other
}
}
我的相关测试:
test("state equality") {
val state = new State( Map(1 -> List("engine"), 2 -> List("a"), 3 -> List("b")) )
expect(true) { state equals state.clone }
expect(true) { state == state.clone }
expect(false) { state == new State(Map(1 -> List("a"))) }
expect(false) { state equals new State(Map(1 -> List("a"))) }
expect(true) { List(state).exists( _.equals (state.clone) )}
expect(true) { List(state).exists( _.== (state.clone) )}
expect(true) { List(state).contains( state.clone )}
}
除了最后一个以外,所有都通过了,但我希望最后一个也能通过。虽然我还没有查看Scala源代码,但我认为contains基本上是实现为第二个exists调用的。
List(state).exists( _ == state.clone )
返回true
,但List(state).exists( _ == (state.clone:Any) )
返回false
。 - Régis Jean-Gillesequals
实现中使用模式匹配比使用isInstanceOf
/asInstanceOf
组合更符合惯用语。 - Régis Jean-Gilles