如何隐式找出无形HList开头的类型

时间:2019-07-09 21:23:01

标签: scala generics shapeless

让我说以下内容:

case class TestField(value: String)
case class TestField2(value: String)

implicit class ProductExtensions[T <: Product](val value T) extends AnyVal {

  def mapTo[R <: Product](implicit tGen: Generic.Aux[T, String :: HNil], rGen: Generic.Aux[R, String :: HNil]: R = ???

}

val testField2 = TestField("my value").mapTo[TestField2]
// TestField2("my value")

是否可以“生成” mapTo函数以用于String以外的其他类型而无需指定类型?

请注意,TestFieldTestField2都实现了AnyVal(我也不想这样做),所以我不能使用Unwrapped

修改

@Dmytro_Mitin答案在上面的示例中有效,但是如果我将示例扩展到此:

implicit class ProductExtensions[T <: Product](val value T) extends AnyVal {

  def mapTo[R <: Product](implicit tGen: Generic.Aux[T, String :: HNil], rGen: Generic.Aux[R, String :: HNil], o: OtherImplicit[String]): R = ???

}

...所以我有点想让它工作(但没有):

implicit class ProductExtensions[T <: Product, U](val value T) extends AnyVal {

  def mapTo[R <: Product](implicit tGen: Generic.Aux[T, U :: HNil], rGen: Generic.Aux[R, U :: HNil], o: OtherImplicit[U]): R = ???

}

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

这是广义版本

implicit class ProductExtensions[T <: Product, L <: HList](val value: T) extends AnyVal {
  def mapTo[R <: Product](implicit tGen: Generic.Aux[T, L], rGen: Generic.Aux[R, L]): R = rGen.from(tGen.to(value))
}

《无形型宇航员指南》。 6.3案例研究:案例类迁移https://books.underscore.io/shapeless-guide/shapeless-guide.html#sec:ops:migration


新版本

import shapeless.ops.hlist.IsHCons

implicit class ProductExtensions[T <: Product, L <: HList, U, L1 <: HList](val value: T) extends AnyVal {
  def mapTo[R <: Product](implicit 
                          tGen: Generic.Aux[T, L], 
                          rGen: Generic.Aux[R, L], 
                          isHCons: IsHCons.Aux[L, U, L1], 
                          o: OtherImplicit[U]
                         ): R = rGen.from(tGen.to(value))
}

4.3链接依赖函数https://books.underscore.io/shapeless-guide/shapeless-guide.html#sec:type-level-programming:chaining

Scala shapeless Generic.Aux implicit parameter not found in unapply