组成隐式推导“律”

问题描述 投票:2回答:1

我正在尝试设计玩具CoversionRate实现,以了解如何通过链接的隐式定义对“法律”进行编码。以下代码编译:

case class ConversionRate[X <: Currency, Y <: Currency](rate: Double) extends AnyVal
object ConversionRate {
  implicit val EUR2USD: ConversionRate[EUR.type, USD.type] = ConversionRate(1.1)
  implicit val GBP2USD: ConversionRate[GBP.type, USD.type] = ConversionRate(1.21)

  // "Laws"
  implicit def inverse[X <: Currency, Y <: Currency](implicit cr: ConversionRate[X, Y]): ConversionRate[Y, X] =
    ConversionRate[Y, X](1 / cr.rate)

  implicit def transitivity[X <: Currency, Z <: Currency](implicit cr: ConversionRate[X, USD.type], cr2: ConversionRate[Z, USD.type]): ConversionRate[X, Z] =
    ConversionRate(cr.rate * cr2.rate)

  private val unit = ConversionRate(1)
  implicit def self[X <: Currency]: ConversionRate[X,X] = unit.asInstanceOf
}

然而,呼叫站点派生确实有效[>]val cr = implicitly[ConversionRate[EUR.type, GBP.type]]

diverging implicit expansion for type ConversionRate[EUR.type,GBP.type]
starting with method transitivity in object ConversionRate
我应该如何以可以用于推导的方式编写法律? 

我正在尝试设计一个玩具CoversionRate实现,以了解如何通过链接的隐式定义对“法则”进行编码。编译以下代码:case类ConversionRate [X

scala implicit-conversion implicit
1个回答
0
投票
隐式无法从规则中得出任何可能的类型,因为它很容易出现在情况中,那么您就有无数种可能性:

id[X]: X => X x: A => B y: B => C

© www.soinside.com 2019 - 2024. All rights reserved.