无形 - 将一个案例类转换为另一个不同顺序的字段

Uta*_*aal 21 scala shapeless labelled-generic

我正在考虑做类似于安全地复制不同类型的案例类之间的字段但使用重新排序的字段,即

case class A(foo: Int, bar: Int)
case class B(bar: Int, foo: Int)
Run Code Online (Sandbox Code Playgroud)

我想有东西转A(3, 4)B(4, 3)-不成形LabelledGeneric浮现在脑海,但是

LabelledGeneric[B].from(LabelledGeneric[A].to(A(12, 13)))
Run Code Online (Sandbox Code Playgroud)

结果是

<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")],Int],shapeless.HNil]]
    (which expands to)  shapeless.::[Int with shapeless.record.KeyTag[Symbol with shapeless.tag.Tagged[String("foo")],Int],shapeless.::[Int with shapeless.record.KeyTag[Symbol with shapeless.tag.Tagged[String("bar")],Int],shapeless.HNil]]
 required: shapeless.::[shapeless.record.FieldType[shapeless.tag.@@[Symbol,String("bar")],Int],shapeless.::[shapeless.record.FieldType[shapeless.tag.@@[Symbol,String("foo")],Int],shapeless.HNil]]
    (which expands to)  shapeless.::[Int with shapeless.record.KeyTag[Symbol with shapeless.tag.Tagged[String("bar")],Int],shapeless.::[Int with shapeless.record.KeyTag[Symbol with shapeless.tag.Tagged[String("foo")],Int],shapeless.HNil]]
              LabelledGeneric[B].from(LabelledGeneric[A].to(A(12, 13)))
                                                           ^
Run Code Online (Sandbox Code Playgroud)

如何重新排序记录中的字段(?),这样可以使用最少的样板?

Tra*_*own 32

我应该把这个留给迈尔斯,但是我很快乐,我无法抗拒.正如他在上面的评论中指出的那样,关键是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]
Run Code Online (Sandbox Code Playgroud)

然后:

case class A(foo: Int, bar: Int)
case class B(bar: Int, foo: Int)
Run Code Online (Sandbox Code Playgroud)

然后:

scala> convertTo[B](A(12, 13))
res0: B = B(13,12)
Run Code Online (Sandbox Code Playgroud)

请注意,在大型案例类的编译时,查找对齐实例将变得昂贵.

  • 这真是太可怕了,感谢特拉维斯,迈尔斯. (5认同)

Dau*_*nnC 13

正如注意到@MilesSabin(神似无形的创造者),有一个对齐操作,它用作:

import ops.hlist.Align

val aGen = LabelledGeneric[A]
val bGen = LabelledGeneric[B]
val align = Align[aGen.Repr, bGen.Repr]
bGen.from(align(aGen.to(A(12, 13)))) //> res0: B = B(13,12)
Run Code Online (Sandbox Code Playgroud)

PS注意到GitHub上有一个例子.