无形定义基本特征的镜头

Shapeless define lens for base trait

我有下一个代码

trait A { val id: Int } 
case class B(id: Int) extends A 
case class C(id: Int, name: String) extends A

我想为所有 class 层级定义通用镜头:

import shapeless._
import lens._ 
val idLens = lens[A] >> 'id

但我得到错误:could not find implicit value for parameter mkLens: shapeless.MkFieldLens[A,Symbol with shapeless.tag.Tagged[String("id")]]

是否可以为trait A的所有children定义镜头?

shapeless 不提供从 ARecord 的隐式转换。您可以定义LabelledGeneric[A]来提供相应的记录类型转换:

import shapeless._
import lens._
import record._
import syntax.singleton._

trait A { val id: Int }
case class B(id: Int) extends A
case class C(id: Int, name: String) extends A

implicit val lgenA = new LabelledGeneric[A] {
  type Repr = Record.`'id -> Int`.T
  def to(a: A) : Repr = ('id ->> a.id) :: HNil
  def from(r: Repr): A = new A { val id = r('id) }
}

val idLens = lens[A] >> 'id

val b = B(7)
println(idLens.get(b)) // 7