这个问题与此问题相关:在Scala中是否可以创建一个类似于Set的类(即它扩展了
测试其是否有效的一种方法是检查
Set
特征),其中用于定义包含关系的相等性是由用户定义而不是==
?测试其是否有效的一种方法是检查
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 verify [T : Equals]
val set = EqualitySet[Coordinate]()
// set2 must be of type EqualitySet[Coordinate]
val set2 = set.filter(_.i > 0)