Этот вопрос связан с этим: возможно ли создать класс Set-like (что означает, что он расширяет черту 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 verify [T : Equals]
val set = EqualitySet[Coordinate]()
// set2 must be of type EqualitySet[Coordinate]
val set2 = set.filter(_.i > 0)