scala – Shapeless – 将案例类别转换为另一个不同顺序的字段
发布时间:2020-12-16 09:38:07 所属栏目:安全 来源:网络整理
导读:我正在考虑做类似于 Safely copying fields between case classes of different types的事情,但是重新排序的字段,即 case class A(foo: Int,bar: Int)case class B(bar: Int,foo: Int) 而我想有一些东西把A(3,4)变成一个B(4,3) – 无形的“LabelledGeneri
我正在考虑做类似于
Safely copying fields between case classes of different types的事情,但是重新排序的字段,即
case class A(foo: Int,bar: Int) case class B(bar: Int,foo: Int) 而我想有一些东西把A(3,4)变成一个B(4,3) – 无形的“LabelledGeneric”,但是, LabelledGeneric[B].from(LabelledGeneric[A].to(A(12,13))) 结果是 <console>:15: error: type mismatch; found : shapeless.::[shapeless.record.FieldType[shapeless.tag.@@[Symbol,String("foo")],Int],shapeless.::[shapeless.record.FieldType[shapeless.tag.@@[Symbol,String("bar")],shapeless.HNil]] (which expands to) shapeless.::[Int with shapeless.record.KeyTag[Symbol with shapeless.tag.Tagged[String("foo")],shapeless.::[Int with shapeless.record.KeyTag[Symbol with shapeless.tag.Tagged[String("bar")],shapeless.HNil]] required: shapeless.::[shapeless.record.FieldType[shapeless.tag.@@[Symbol,shapeless.HNil]] (which expands to) shapeless.::[Int with shapeless.record.KeyTag[Symbol with shapeless.tag.Tagged[String("bar")],shapeless.::[Int with shapeless.record.KeyTag[Symbol with shapeless.tag.Tagged[String("foo")],shapeless.HNil]] LabelledGeneric[B].from(LabelledGeneric[A].to(A(12,13))) ^ 如何重新排序记录中的字段(?),这样可以使用最少的样板? 解决方法
我应该离开这里为里程,但我是快乐的时光,我来自我,我无法抗拒。正如他在上面的评论中指出的那样,关键是ops.hlist.Align,这对于记录(这些只是特殊的hlists)都是正常的。
如果你想要一个很好的语法,你需要使用下面的技巧,将类型参数列表与类型参数列表中的所有其他内容(你想要推断的目标) ): import shapeless._,ops.hlist.Align 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] 接着: case class A(foo: Int,foo: Int) 接着: scala> convertTo[B](A(12,13)) res0: B = B(13,12) 请注意,在大型案例类的编译时,查找对齐实例将会变得昂贵。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |