假设以下特征:
trait A {
type B
}
有没有办法将它变成一个有序类型,只能比较具有相同B的A,这是在编译时强制执行的?
答案 0 :(得分:4)
是的,通过隐式(使用类型别名使事情变得更干),
type AA[T] = A { type B = T }
implicit def aIsOrdered[T](a : AA[T]) = new Ordered[AA[T]] {
def compare(that : AA[T]) = 0
}
示例REPL会话,
scala> val ai1 = new A { type B = Int }
ai1: java.lang.Object with A{type B = Int} = $anon$1@1ec264c
scala> val ai2 = new A { type B = Int }
ai2: java.lang.Object with A{type B = Int} = $anon$1@1a8fb1b
scala> val ad = new A { type B = Double }
ad: java.lang.Object with A{type B = Double} = $anon$1@891a0
scala> ai1 < ai2
res2: Boolean = false
scala> ai1 < ad
<console>:16: error: type mismatch;
found : ad.type (with underlying type java.lang.Object with A{type B = Double})
required: AA[Int]
ai1 < ad
^
编辑...
由于scala.math.LowPriorityOrderingImplicits中的隐式定义,这个定义足以为我们提供相应的Ordering类型类实例。这允许我们将A用于需要排序的类型,例如。一个scala.collection.SortedSet,
scala> implicitly[Ordering[AA[Int]]]
res0: Ordering[AA[Int]] = scala.math.LowPriorityOrderingImplicits$$anon$4@39cc63
scala> import scala.collection.SortedSet
import scala.collection.SortedSet
scala> val s = SortedSet(ai1, ai2)
s: scala.collection.SortedSet[java.lang.Object with A{type B = Int}] = TreeSet($anon$1@1a8fb1b)
答案 1 :(得分:0)
如何使B
成为A
的参数?
trait A[B] {
compare(x: A[B]): Int
}