我正在尝试将我的case类转换为包含每个字段镜头的序列。我创建了以下简化示例来突出我遇到的问题。
以下代码将给出运行时错误:
import shapeless._
case class Testing(field1: String, field2: Double)
val lenses = Seq(0,1).map(i => lens[Testing] >> i)
而以下情况则不然:
import shapeless._
case class Testing(field1: String, field2: Double)
val lens1 = lens[Testing] >> 0
val lens2 = lens[Testing] >> 1
val lenses = Seq(lens1, lens2)
实际错误读取"表达式i不评估为非负Int文字"。
我觉得这个错误信息是误导的,因为代码val lens3 =镜头[测试]>> 2(即访问一个字段太多)会给出相同的错误信息。
有没有人在无形中经历过这样的行为?是否有更简单的方法将我的Case Class中每个字段的元素镜头提取到一个序列中(即不像单片格中的@lenses,你还需要使用字段名称访问每个镜头)?
答案 0 :(得分:0)
lens[Testing] >> 0
lens[Testing] >> 1
隐式转换为
lens[Testing] >> Nat._0
lens[Testing] >> Nat._1
这可行,但
val lenses = Seq(0,1).map(i => lens[Testing] >> i)
或val lenses = Seq(Nat._0,Nat._1).map(i => lens[Testing] >> i)
没有。
Seq(Nat._0,Nat._1)
的类型为Seq[Nat]
,因此i
的类型为Nat
(而不是特定的Nat._0
,Nat._1
),这太粗糙了
构建HList
镜头(而非Seq
)的以下方法似乎有效:
import shapeless.{::, Generic, HList, HNil, Lens, MkHListSelectLens}
case class Testing(field1: String, field2: Double)
trait MkLensHlist[A] {
type Out <: HList
def apply(): Out
}
object MkLensHlist {
type Aux[A, Out0 <: HList] = MkLensHlist[A] { type Out = Out0 }
def instance[L, Out0 <: HList](x: Out0): Aux[L, Out0] = new MkLensHlist[L] {
override type Out = Out0
override def apply(): Out0 = x
}
def apply[A](implicit instance: MkLensHlist[A]): instance.Out = instance()
implicit def mk[A, L <: HList, Out <: HList](implicit
gen: Generic.Aux[A, L],
apply: ApplyMkHListSelectLens.Aux[L, Out]
): Aux[A, Out] = instance(apply())
}
trait ApplyMkHListSelectLens[L <: HList] {
type Out <: HList
def apply(): Out
}
object ApplyMkHListSelectLens {
type Aux[L <: HList, Out0 <: HList] = ApplyMkHListSelectLens[L] { type Out = Out0}
def instance[L <: HList, Out0 <: HList](x: Out0): Aux[L, Out0] = new ApplyMkHListSelectLens[L] {
override type Out = Out0
override def apply(): Out0 = x
}
implicit def mk[L <: HList, Out <: HList](implicit
apply: ApplyMkHListSelectLens1.Aux[L, L, Out]
): Aux[L, Out] =
instance(apply())
}
trait ApplyMkHListSelectLens1[L <: HList, L1 <: HList] {
type Out <: HList
def apply(): Out
}
object ApplyMkHListSelectLens1 {
type Aux[L <: HList, L1 <: HList, Out0 <: HList] = ApplyMkHListSelectLens1[L, L1] { type Out = Out0}
def instance[L <: HList, L1 <: HList, Out0 <: HList](x: Out0): Aux[L, L1, Out0] = new ApplyMkHListSelectLens1[L, L1] {
override type Out = Out0
override def apply(): Out0 = x
}
implicit def mk1[L <: HList, H, T <: HList, Out <: HList](implicit
lens: MkHListSelectLens[L, H],
apply: Aux[L, T, Out]
): Aux[L, H :: T, Lens[L, H] :: Out] =
instance(lens() :: apply())
implicit def mk2[L <: HList]: Aux[L, HNil, HNil] =
instance(HNil)
}
MkLensHlist[Testing]
// shapeless.MkHListSelectLens$$anon$36$$anon$17@340f438e :: shapeless.MkHListSelectLens$$anon$36$$anon$17@30c7da1e :: HNil