给定一个任意case class Cc( a: String, b: Int )
和一个类型类trait Tc[T]
,有没有办法实现一个简单的HList
(或最好是一个标记的记录),它包含每个参数的类型类实例是Cc
?
def resolveTypeClasses[C] = ???
val resolved: Tc[String] :: Tc[Int] :: HNil = resolveTypeClasses[Cc]
答案 0 :(得分:3)
由于需要解析中间Generic
,很难制作单一类型参数功能。
因此,从我的noob观点来看,它应该是两个参数def
,或两个def
的序列,每个都采用单一类型参数。第二种变体可以实现如下:
import shapeless._
trait Tc[T]
case class Cc(a: String, b: Int)
trait ResolveTC[L] {
type Out <: HList
val out: Out
}
implicit object ResolveHNilTC extends ResolveTC[HNil] {
type Out = HNil
val out: HNil = HNil
}
implicit def resolveHListTC[X, XS <: HList](implicit tc: Tc[X], rest: ResolveTC[XS]) =
new ResolveTC[X :: XS] {
type Out = Tc[X] :: rest.Out
val out = tc :: rest.out
}
class TCResolver[C] {
def get[L <: HList](implicit gen: Generic.Aux[C, L], resolve: ResolveTC[L]): resolve.Out = resolve.out
}
def resolveTypeClasses[C] = new TCResolver[C]
implicit case object StringInst extends Tc[String]
implicit case object IntInst extends Tc[Int]
使用该实现
val resolved = resolveTypeClasses[Cc].get
将产生
StringInst :: IntInst :: HNil