如果我有一个方法,比如:
def f[T: Generic, U: Generic](t: T): UGeneric[T].to(t)返回类型Generic[T]#Repr,我假设它是某种类型HList的类型别名。
是否可以从HList中选择成员并构建另一个HList,我可以确信编译器是Generic[U]#Repr类型的,然后可以使用该类型通过Generic[U].from(myNewHList)创建U的实例
我尝试了许多方法,但似乎都在兜圈子。
发布于 2019-03-15 02:49:55
在Shapeless中做这样的事情时,最好的地方是在shapeless.ops类型类中。在这种情况下,因为您知道第二个类是第一个类的严格子集,所以Intersection就足以获得您想要的东西。您需要将其设置为一个类型类,以便可以传入输入和输出类型,并让编译器推断中间内容。
trait Converter[A,B] {
def convert(a: A): B
}
object Converter {
def apply[A,B](implicit converter: Converter[A,B]) = converter
implicit def genericConverter[A, B, ARepr <: HList, BRepr <: HList](
implicit
genA: Generic.Aux[A,ARepr],
genB: Generic.Aux[B,BRepr],
intersection: shapeless.ops.hlist.Intersection.Aux[ARepr,BRepr,BRepr]
): Converter[A,B] =
new Converter[A,B]{def convert(a: A): B = genB.from(intersection(genA.to(a)))}
}它的用法如下:
case class Foo(a: Int, b: Int, c: String)
case class Bar(a: Int, c: String)
val foo = Foo(1,2,"Three")
val bar: Bar = Converter[Foo, Bar].convert(foo)https://stackoverflow.com/questions/55167713
复制相似问题