scala - 在 unapply 中找不到 Scala 无形 Generic.Aux 隐式参数
问题描述
我在 Scala 中遇到了以下使用 Shapeless 的隐式问题Generic.Aux
:
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]]
导出这个隐式实例是完全可以的。
解决方案
以下代码有效:
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
推荐阅读
- python-3.x - 如何将 excel/csv 文件作为函数参数传递?
- php - 按产品名称获取产品 ID(转义特殊字符)
- c# - 运行 Scaffold DBContext 而不覆盖实体框架核心中的自定义代码
- android - 如何解决 Kotlin 的膨胀类错误?
- javascript - 更新 mobx 存储值后,组件的 render() 没有被调用
- angular - 类构造函数 AnimationEngine 不能在没有 new 的情况下被调用
- kibana - 在 Elastalert 计划间隔选项中丢失
- ionic-framework - 离子标头,如何使用整个屏幕
- python - 通过按索引省略值来过滤列表
- list - 使用 Python 的龙与地下城字符表生成器