Skip to content

Instantly share code, notes, and snippets.

@gigiigig
Last active August 29, 2015 14:21
Show Gist options
  • Save gigiigig/d9abab81ed6930a5474e to your computer and use it in GitHub Desktop.
Save gigiigig/d9abab81ed6930a5474e to your computer and use it in GitHub Desktop.
Update a field by name for any case class
object console extends App {
import shapeless._
import syntax.singleton._
import record._
case class Foo(s: String, id: Int)
case class Bar(id: Int, b: Boolean)
case class Ciao(d: Double)
implicit class RichProduct[P <: Product](p: P) {
val w = Witness('id)
def updateId[V, R, L <: HList](id: Int)(
implicit g: LabelledGeneric.Aux[P, L],
s: ops.record.Selector.Aux[L, w.T, V],
u: ops.record.Updater.Aux[L, record.FieldType[w.T, Int], L]
) = {
val l = g.to(p)
val r = l.updated('id, id)
g.from(r)
}
}
val f = Foo("ddd", 1).updateId(3)
val b = Bar(1, false).updateId(3)
// val d = Ciao(4d).updateId(4) // doesn' t compile
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment