im trying to figure out how to express the code below using abstract types, instead of using type parameters.
trait Key[T] extends Ordered[Key[T]] {
val key:T
}
case class DoubleKey(key:Double) extends Key[Double] {
def compare(that:Key[Double]):Int = this.key compare that.key
}
My current version is as follows:
trait Key extends Ordered[Key] {
type K
val key:K
}
case class DoubleKey(val key:Double) extends Key {
type K = Double
def compare(that:Key):Int = this.key compare that.key.asInstanceOf[K]
}
But I'm not happy with the explicit cast to type K : that.key.asInstanceOf[K]. Are there better / other ways to achieve ordering of an abstract element using abstract types?
I also tried to make sure that the type that:Keyis Double:
def compare(that:Key { type K = Double } ):Int = this.key compare that.key
but this also fails because the compiler does not consider the comparison to be defined. In addition, is there a solution in which compareyou can transfer to a key key by restricting K (for example, type K <: Ordered[K])?
source
share