Assumi la seguente caratteristica:
trait A {
type B
}
C'è un modo per farlo in un tipo ordinato, in cui solo A "s con lo stesso B" può essere confrontato, e questo viene applicato in fase di compilazione?
risposte:
4 per risposta № 1Sì, tramite un implicito (con un alias di tipo per rendere le cose un po 'più ASCIUTTE),
type AA[T] = A { type B = T }
implicit def aIsOrdered[T](a : AA[T]) = new Ordered[AA[T]] {
def compare(that : AA[T]) = 0
}
Esempio di sessione 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
^
Modificare ...
Grazie alle definizioni implicite in scala.math.LowPriorityOrderingImplicits questa definizione è sufficiente per fornirci istanze di classe del tipo di ordine corrispondente. Questo ci permette di usare A con tipi che richiedono Ordini, es. 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)
0 per risposta № 2
Che ne dici di fare B
un parametro di A
?
trait A[B] {
compare(x: A[B]): Int
}