Last active
August 29, 2017 11:10
-
-
Save calippo/562cb176437ff264ec4e8b888d55143f to your computer and use it in GitHub Desktop.
Given a sealed trait A and a case class B, force the case class to have as parameters all and only the known subclasses of A (at compile time with shapeless)
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
import shapeless._ | |
sealed trait A | |
case object A1 extends A | |
case object A2 extends A | |
case object A3 extends A | |
case class B( | |
A1: String, | |
A2: String, | |
A3: String | |
) | |
val b = B("a", "b", "c") | |
class CaseClassLink[A, B] { | |
def am[V <: HList, K <: HList, L <: HList, H <: HList, C <: Coproduct](b: B)(implicit | |
bGen: LabelledGeneric.Aux[B, H], | |
values: shapeless.ops.record.Values.Aux[H, V], | |
kGen: LabelledGeneric.Aux[A, C], | |
keys: ops.union.Keys.Aux[C, K], | |
zip: ops.hlist.ZipWithKeys.Aux[K, V, L], | |
b2Gen: LabelledGeneric.Aux[B, L] | |
): B = { | |
val k: K = keys() | |
val v: V = values(bGen.to(b)) | |
val l: L = v.zipWithKeys(k) | |
b2Gen.from(l) | |
} | |
} | |
val x = (new CaseClassLink[A, B]).am(b) | |
println(x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment