我试图将这里描述的使用值类实现类型安全的想法扩展到一个更抽象的版本,它允许隐式转换。例如,我有一些度量特征
trait Measure {
implicit def +[B <: Measure](other: B): Measure
val value: Double
}和一些实现
//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) }以及一种用于隐式查找机制的转换器特性和实现
trait Converter[F, T]{
val factor: Double
}
implicit object Meter2Fathom extends Converter[Meter, Fathom]{
val factor: Double = .556
}
implicit object Fathom2Meter extends Converter[Fathom, Meter]{
val factor: Double = 1.8
}有没有办法在“不管B是什么”上定义Converter实现?如果我们尝试将两个不存在转换因子的度量相加,但仍然能够编译,我希望出现运行时错误。
//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发布于 2015-02-06 23:16:33
据我所知你想要的是磁铁图案。这里有一个内容广泛的博客:http://spray.io/blog/2012-12-13-the-magnet-pattern/
https://stackoverflow.com/questions/28361648
复制相似问题