繁体   English   中英

有没有办法以通用方式将 Hlist 转换为适当的案例 class ?

[英]Is there a way to convert Hlist to an appropriate case class in a generic way?

我看过 Travis Brown 提出的很酷的解决方案,它允许以通用方式在彼此之间转换案例类。 我尝试使用它将HList转换为case class ,但没有成功。 这是我的尝试:

import shapeless._, ops.hlist.Align
import syntax.std.tuple._

object Shplss  extends App {
  class SameFieldsConverter[T] {
    def apply[S, SR <: HList, TR <: HList](s: S)(implicit
                                                 genS: LabelledGeneric.Aux[S, SR],
                                                 genT: LabelledGeneric.Aux[T, TR],
                                                 align: Align[SR, TR]
    ) = genT.from(align(genS.to(s)))
  }

  def convertTo[T] = new SameFieldsConverter[T]

  type SomeType = Int :: Int :: String :: Boolean :: Int :: Int :: HNil
  final case class SomeProductType(f1: Int, f2: Int, f3: String, f4: Boolean, f5: Int, f6: Int)

  val some: SomeType = (4, 4, "ssdf", true, 2, 4).productElements

  convertTo[SomeProductType](some)
}

不幸的是,它失败并出现错误:

Error:(22, 29) could not find implicit value for parameter genS: shapeless.LabelledGeneric.Aux[com.test.Shplss.SomeType,SR]
  convertTo[SomeProductType](some)


Error:(22, 29) not enough arguments for method apply: (implicit genS: shapeless.LabelledGeneric.Aux[com.test.Shplss.SomeType,SR], implicit genT: shapeless.LabelledGeneric.Aux[com.test.Shplss.SomeProductType,TR], implicit align: shapeless.ops.hlist.Align[SR,TR])com.test.Shplss.SomeProductType in class SameFieldsConverter.
Unspecified value parameters genS, genT, align.
  convertTo[SomeProductType](some)

有没有办法增强 converTo converTo[B] function 以便它也可以在HList之间转换?

Shapeless 的GenericLabelledGeneric是类型类,它们使用 hlists 和 coproducts 为案例类和密封特征层次结构提供通用表示。 如果您已经有一个 hlist,那么您实际上并不需要Generic实例,Shapeless 也不提供。 在您的情况下,这意味着您实际上可以跳过genSSR部分:

import shapeless._, ops.hlist.Align
import syntax.std.tuple._

object Shplss  extends App {
  class SameFieldsConverter[T] {
    def apply[S <: HList, TR <: HList](s: S)(implicit
      genT: Generic.Aux[T, TR],
      align: Align[S, TR]
    ) = genT.from(align(s))
  }

  def convertTo[T] = new SameFieldsConverter[T]

  type SomeType = Int :: Int :: String :: Boolean :: Int :: Int :: HNil
  final case class SomeProductType(f1: Int, f2: Int, f3: String, f4: Boolean, f5: Int, f6: Int)

  val some: SomeType = (4, 4, "ssdf", true, 2, 4).productElements

  convertTo[SomeProductType](some)
}

正如您所期望的,这将为您提供SomeProductType(4,4,ssdf,true,2,4)

请注意,我已将genTLabelledGeneric更改为Generic ,因为我们不再需要在输入端对齐标签。 我想您可以添加一些额外的机制来将未标记的输入“注入”到无形记录中以匹配LabelledGeneric类型,但在这个特定的用例中至少没有任何意义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM