这个问题关系到这一个:是否有可能创建一组类的类(意思是它的扩展Set特性)Scala中,其中使用的平等来定义包含关系是由用户,而不是被定义的==?
测试这是否真的有效的一种方法是检查是否filter返回相同的集合类型.
// typeclass for equality
trait Equals[T] {
def isEqual(t1: T, t2: T): Boolean
}
// an object representing plane coordinates
case class Coordinate(i: Int, j: Int)
// an equality saying that 2 coordinates are equal if they are on
// the same horizontal line
implicit def horizontalEquality: Equals[Coordinate] = new Equals[Coordinate] {
def isEqual(t1: Coordinate, t2: Coordinate) = t1.i == t2.i
}
// we create an EqualitySet[T] where T must …Run Code Online (Sandbox Code Playgroud) 我有一个案例类Foo定义如下.我想覆盖其中的行为==,以便optBar在比较中忽略最后一个元素().这是我尝试过的,似乎有效.
case class Bar(i:Int)
case class Foo(i:Int, s:String, optBar:Option[Bar]) {
override def equals(o:Any) = o match {
case Foo(`i`, `s`, _) => true
case _ => false
}
override def hashCode = i.hashCode*997 ^ s.hashCode * 991
}
val b = Bar(1)
val f1 = Foo(1, "hi", Some(b))
val f2 = Foo(1, "hi", None)
f1 == f2 // true
Run Code Online (Sandbox Code Playgroud)
我想知道的是创建方法hashCode是否正确.我从这个链接得到了它.