首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Scala:使用类型类惯用法进行隐式值查找

Scala:使用类型类惯用法进行隐式值查找
EN

Stack Overflow用户
提问于 2015-02-06 16:37:32
回答 1查看 343关注 0票数 0

我试图将这里描述的使用值类实现类型安全的想法扩展到一个更抽象的版本,它允许隐式转换。例如,我有一些度量特征

代码语言:javascript
复制
trait Measure {
implicit def +[B <: Measure](other: B): Measure
val value: Double
}

和一些实现

代码语言:javascript
复制
//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) }

以及一种用于隐式查找机制的转换器特性和实现

代码语言:javascript
复制
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实现?如果我们尝试将两个不存在转换因子的度量相加,但仍然能够编译,我希望出现运行时错误。

代码语言:javascript
复制
//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
EN

回答 1

Stack Overflow用户

发布于 2015-02-06 23:16:33

据我所知你想要的是磁铁图案。这里有一个内容广泛的博客:http://spray.io/blog/2012-12-13-the-magnet-pattern/

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28361648

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档