Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shapeless define lens for base trait

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?

like image 294
lito Avatar asked Sep 29 '15 18:09

lito


1 Answers

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
like image 178
devkat Avatar answered Nov 07 '22 16:11

devkat