scala - Defining an ordering on traits with abstract types which compiles only for compatible types? -
assume following trait:
trait { type b }
is there way of making ordered type, a's same b's can compared, , enforced in compile time?
yes, via implicit (with type alias make things little more dry),
type aa[t] = { 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 { type b = int } ai1: java.lang.object a{type b = int} = $anon$1@1ec264c scala> val ai2 = new { type b = int } ai2: java.lang.object a{type b = int} = $anon$1@1a8fb1b scala> val ad = new { type b = double } ad: java.lang.object 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 a{type b = double}) required: aa[int] ai1 < ad ^
edit ...
thanks implicit definitions in scala.math.lowpriorityorderingimplicits defintion sufficient provide corresponding ordering type class instances. allows use types require orderings, eg. 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 a{type b = int}] = treeset($anon$1@1a8fb1b)
Comments
Post a Comment