开发者

Defining an ordering on traits with abstract types which compiles only for compatible types?

Assume the following trait:

trait A {
  type B       
}

Is there any way of mak开发者_开发百科ing this into an ordered type, where only A's with the same B's can be compared, and this is enforced in compile time?


Yes, via an implicit (with a type alias to make things a little more DRY),

type AA[T] = A { type B = T }

implicit def aIsOrdered[T](a : AA[T]) = new Ordered[AA[T]] {
  def compare(that : AA[T]) = 0
}

Sample REPL session,

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
             ^

Edit ...

Thanks to the implicit definitions in scala.math.LowPriorityOrderingImplicits this defintion is sufficient to provide us with corresponding Ordering type class instances. This allows us to use A with types which require Orderings, eg. 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)


How about making B a parameter of A?

trait A[B] {
    compare(x: A[B]): Int
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜