【问题标题】:How to implicitly figure out the type at the head of a shapeless HList如何隐式找出无形 HList 头部的类型
【发布时间】:2019-11-19 11:44:21
【问题描述】:

假设我有以下内容:

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 = ???

}

有什么想法吗?

【问题讨论】:

    标签: scala generics shapeless


    【解决方案1】:

    这里是通用版

    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))
    }
    

    Type 宇航员无形指南。 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

    【讨论】:

    • 啊,我试过了,但 IntelliJ 似乎不喜欢它……但它确实可以编译!
    • @Cheetah Intellij 不喜欢很多东西
    • 哈哈 - 就其价值而言,我的实现很好......使用 Unwrapped 和 AnyVal 也很好
    • @DmytroMitin - 我有一个类似的场景,我实际上需要将L 输入为String(而不是String :: HNil)作为另一个隐式 - 这可能吗?
    • @Cheetah 你可以阅读4.3 Chaining dependent functions关于过度约束的隐式。
    猜你喜欢
    • 2014-06-03
    • 2021-02-18
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多