在未应用中找不到Scala无形状的Generic.Aux隐式参数

时间:2019-01-30 02:13:52

标签: scala shapeless unapply

我使用Shapeless的Generic.Aux在Scala中遇到了以下隐式问题:

  case class Complex(re: Double, im: Double)

  object Prod2 {
    def unapply[C, A, B](c: C)(implicit C: Generic.Aux[C, A :: B :: HNil]) = Some((C.to(c).head, C.to(c).tail.head))
  }

  val c = Complex(1.0, 2.0)
  val Prod2(re, im) = c

上面的代码无法编译。报告

Error:(22, 7) could not find implicit value for parameter C: shapeless.Generic.Aux[nexus.ops.Test.Complex,A :: B :: shapeless.HNil]
  val Prod2(re, im) = c
Error:(22, 7) not enough arguments for method unapply: (implicit C: shapeless.Generic.Aux[nexus.ops.Test.Complex,A :: B :: shapeless.HNil])Some[(A, B)].
Unspecified value parameter C.
  val Prod2(re, im) = c

但是,如果我手动执行

implicitly[Generic.Aux[Complex, Double :: Double :: HNil]]

完全可以派生此隐式实例。

2 个答案:

答案 0 :(得分:1)

以下代码有效:

import shapeless.ops.hlist.IsHCons
import shapeless.{::, Generic, HList, HNil}

case class Complex(re: Double, im: Double)

object Prod2 {
  def unapply[C, L <: HList, H, T <: HList, H1, T1 <: HList](c: C)(implicit
    C: Generic.Aux[C, L],
    isHCons: IsHCons.Aux[L, H, T],
    isHCons1: IsHCons.Aux[T, H1, T1]) = Some((C.to(c).head, C.to(c).tail.head))
}

val c = Complex(1.0, 2.0)
val Prod2(re, im) = c

答案 1 :(得分:1)

不幸的是,编译器根本不够聪明,无法执行在这里推断AB所必需的统一。您可以在Underscore's Type Astronaut’s Guide to Shapeless的第4.3节中了解有关此问题的一些详细信息。本书提供了使用IsHCons的解决方法,但在这种情况下,我认为要求<:<证明会更简洁:

import shapeless.{::, Generic, HList, HNil}

case class Complex(re: Double, im: Double)

object Prod2 {
  def unapply[C, L <: HList, A, B](c: C)(implicit
    C: Generic.Aux[C, L],
    ev: L <:< (A :: B :: HNil)
  ) = Some((C.to(c).head, C.to(c).tail.head))
}

然后:

scala> val c = Complex(1.0, 2.0)
c: Complex = Complex(1.0,2.0)

scala> val Prod2(re, im) = c
re: Double = 1.0
im: Double = 2.0

令人失望,但是如果您与Shapeless一起使用,这是您需要反复解决的一种解决方法,因此最好将其放在工具箱中。