基于类型递归转换无形记录中的元素

时间:2016-04-30 08:20:30

标签: scala shapeless

如何在Poly1上递归应用Record?我已经指出everywhere,但这似乎与Record的效果不太好。

object f extends Poly1 { implicit def atFoo = at[Foo](x => x) }
sealed trait Foo
case class Foo1(foo: Foo) extends Foo
case class Foo2(int: Int) extends Foo
def m = {
  val generic = LabelledGeneric[Foo]
  generic.from(everywhere(f)(generic.to(Foo1(Foo1(Foo2(3))))))
}

给我

[error]  found   : generic.Repr
[error]     (which expands to)  shapeless.:+:[Main.Foo1 with shapeless.labelled.KeyTag[Symbol with shapeless.tag.Tagged[String("Foo1")],Main.Foo1],shapeless.:+:[Main.Foo2 with shapeless.labelled.KeyTag[Symbol with shapeless.tag.Tagged[String("Foo2")],Main.Foo2],shapeless.CNil]]
[error]  required: shapeless.poly.Case[_1.type,shapeless.HNil]{type Result = ?} where val _1: shapeless.EverywhereAux[Main.f.type]
[error]     generic.from(everywhere(f)(generic.to(Foo1(Foo1(Foo2(3))))))
[error]                                          ^

http://scastie.org/16713

1 个答案:

答案 0 :(得分:1)

使用LabelledGeneric时,您无需直接致电everywhere。它为您处理HList转换,因此您可以将其称为everywhere(f)(Foo1(Foo1(Foo2(3))))。我将其更改为修改Int字段,以便您可以清楚地看到它正常工作:

import shapeless._

object f extends Poly1 {
  implicit def atFoo = at[Int](_ * 2)
}

sealed trait Foo
case class Foo1(foo: Foo) extends Foo
case class Foo2(int: Int) extends Foo

println(everywhere(f)(Foo1(Foo1(Foo2(3)))))