Last active
August 29, 2015 14:21
-
-
Save gigiigig/d9abab81ed6930a5474e to your computer and use it in GitHub Desktop.
Update a field by name for any case class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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