I am attempting to extend the idea of using value classes for type safety as described here http://ift.tt/VqBnbO to a more abstract version that allows implicit conversions. For example, I have some Measure trait
trait Measure {
implicit def +[B <: Measure](other: B): Measure
val value: Double
}
and some implementations
//this will compile because [_ , Meters] is not ambiguous since
//for this example im only using one conversion. see below
case class Meters(value: Double) extends Measure {
def +[B <: Measure](other: B): Meters = Meters(other.value * implicitly[Converter[_ , Meters]].factor + this.value) }
case class Fathoms(value: Double) extends Measure {
def +[B <: Measure](other: B): Fathoms = Fathoms(other.value * implicitly[Converter[_ , Fathoms]].factor + this.value) }
and a converter trait and implementation for the implicit lookup mechanism to find
trait Converter[F, T]{
val factor: Double
}
object Meter2Fathom extends Converter[Meter, Fathom]{
val factor: Double = .556
}
object Fathom2Meter extends Converter[Fathom, Meter]{
val factor: Double = 1.8
}
Is there a way to define Converter implementations on "whatever B is"? I want run time error if we try to add together two measures for which there doesnt exist a conversion factor, but still be able to compile.
//will not compile of course. the idea is to somehow reify whatever B
// is and look that implicit converter up, instead of actual B.
case class Meters(value: Double) extends Measure {
def +[B <: Measure](other: B): Meters = Meters(this.value + other.value * implicitly[Converter[* B *, Meters]].factor
Aucun commentaire:
Enregistrer un commentaire