【问题标题】:AUX pattern workaroundAUX 模式解决方法
【发布时间】:2018-06-22 06:21:29
【问题描述】:

这是一个源自AUX 模式的问题。

这样定义特征有什么好处:

trait Unwrap[T[_], R] {
   type Out
   def apply(tr: T[R]): Out
}

与此相反?

trait Unwrap[T[_], R, Out] {
   def apply(tr: T[R]): Out
}

第二个特征定义消除了使用 AUX 模式的必要性。

谢谢!

【问题讨论】:

    标签: scala


    【解决方案1】:

    您使用Aux 模式的原因在您的示例中没有明确定义。当Aux 提供的类型的值尚不知道时,问题就出现了,这在大多数情况下意味着派生,更具体地说是宏/编译时类型派生。

    这在Shapeless中被广泛使用。

    def test[V1, HL](input: V1)(implicit ev: Generic.Aux[V1, HL])`
    

    当你写这篇文章时,你可能会认为HLAux 的输入类型,但它实际上是Generic 宏内的输出,作为Aux 的消耗品提供,例如输出是神奇的“注入”到 HL 中,因此由 Generic.Aux 计算的输出类型可通过该调用站点之外的 HL 访问。

    如果您在同一个参数组中有多个隐式,则存在绕过编译器限制,其中一个隐式取决于前一个的 Aux 宏输出。

    The Scala Bible, New Testament, Gospel of Miles粘贴:

     * More importantly, Aux allows us to write code like this:
       *
       * {{{
       *   def myMethod[T, R]()(implicit eqGen: Generic.Aux[T,R], repEq: Eq[R]) = ???
       * }}}
       *
       * Here, we specify T, and we find a Generic.Aux[T,R] by implicit search. We then use R in the second argument.
       * Generic.Aux[T, R] is exactly equivalent to Generic[T] { type Repr = R }, but Scala doesn't allow us to write
       * it this way:
       *
       * {{{
       *   def myMethod[T, R]()(eqGen: Generic[T] { Repr = R }, reqEq: Eq[egGen.Repr]) = ???
       * }}}
    

    【讨论】:

      猜你喜欢
      • 2015-06-01
      • 1970-01-01
      • 2013-08-16
      • 2014-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-03
      • 1970-01-01
      相关资源
      最近更新 更多