I have the next code
trait A { val id: Int }
case class B(id: Int) extends A
case class C(id: Int, name: String) extends A
i want to define common lens for all class hierarchy:
import shapeless._
import lens._
val idLens = lens[A] >> 'id
But i get error: could not find implicit value for parameter mkLens: shapeless.MkFieldLens[A,Symbol with shapeless.tag.Tagged[String("id")]]
Is it possible to define lens for all children of trait A
?
shapeless doesn't provide an implicit conversion from A
to Record
. You could define LabelledGeneric[A]
to provide the corresponding record type conversion:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With