给定一个依赖于类型的 Converter 类型类,它可以将 String 转换为 Integer:
trait Converter[From] {
type To
def to(from: From): To
}
object Converter {
type Aux[From, Out0] = Converter[From] { type To = Out0 }
implicit val forInteger = new Converter[Integer] {
type To = String
def to(value: Integer) = ???
}
}
// this works
val single = the[Converter[Integer]]
implicitly[single.To =:= String]
val singleAux = the[Converter.Aux[Integer, String]]
我希望它适用于 HList,例如Integer :: HNil
. 理论上,我只需要隐含 HNil 和 HList:
implicit val forHNil = new Converter[HNil] {
type To = HNil
def to(value: HNil) = HNil
}
implicit def forHList[Head, HeadConverted, Tail <: HList, TailConverted <: HList](
implicit
hConverter: Converter.Aux[Head, HeadConverted],
tConverter: Converter.Aux[Tail, TailConverted]
): Converter[Head :: Tail] = new Converter[Head :: Tail] {
type To = HeadConverted :: TailConvertedHList
def to(values: Head :: Tail) = ???
}
以上适用于 HNil:
val hnil = the[Converter[HNil]]
implicitly[hnil.To =:= HNil]
val hnilAux = the[Converter.Aux[HNil, HNil]]
但不适用于 HList。有趣的是,它确实找到了一个实例,但没有派生出结果类型
val hlist = the[Converter[Integer :: HNil]]
type expected = String :: HNil
implicitly[hlist.To =:= expected] //fails
val hlistAux = the[Converter.Aux[Integer :: HNil, String :: HNil]] // fails
我已经将它设置在一个自包含的项目中,该项目有更多(失败)尝试调试问题:https ://github.com/mpollmeier/shapeless-dependent-type-typeclass-problem