I am trying to create a type class that will allow me to increment an Int field called "counter" for any case class if that class has such a field.
I tried to do this with Shapeless, but I hit the walls (first I tried to digest the Lifeless Astronaut Guide), Shapeless 2.0.0 Feature Overview, and numerous threads in the stack overflow).
I want to be able to do something like
case class MyModel(name:String, counter:Int) {}
val instance = MyModel("Joe", 4)
val incremented = instance.increment()
assert(incremented == MyModel("Joe", 5))
And it should work for any case class with a suitable counter field.
I thought this was possible using a type class and Shapeless notation abstraction (and implicit conversion to get extra functionality added as a method). The bare bones will be something like this:
trait Incrementer[T] {
def inc(t:T): T
}
object Incrementer {
import shapeless._ ; import syntax.singleton._ ; import record._
implicit def getIncrementer[T](implicit generator: LabelledGeneric[T]): Incrementer[T] = new Incrementer[T] {
def inc(t:T) = {
val repr = generator.to(t)
generator.from(repr.replace('counter, repr.get('counter) + 1))
}
}
}
. value replace is not a member of generator.Repr. , , , T counter Int. ? / Shapeless? ?