Created
August 20, 2015 14:58
-
-
Save ahoy-jon/b9e0cdf837858efa287f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
package datalab.pj | |
import shapeless.ops.hlist.ToTraversable | |
import shapeless.ops.record._ | |
import shapeless.record._ | |
import shapeless.{HList, LabelledGeneric} | |
// Recursive versions for Nested Case Classes exist | |
object CaseClassToMap { | |
case class A(name: String, age: Int) | |
implicit class ToMapRecOps[A <: Product](val a: A) extends AnyVal { | |
def toMapRec[L <: HList, KS <: HList, VS <: HList](implicit gen: LabelledGeneric.Aux[A, L], | |
keys: Keys.Aux[L, KS], | |
values: Values.Aux[L, VS], | |
ts1: ToTraversable.Aux[KS, List, Symbol], | |
ts2: ToTraversable.Aux[VS, List, Any]): Map[String, Any] = { | |
val r = gen.to(a) | |
r.keys.to[List].map(_.name).zip(r.values.to[List]).toMap | |
} | |
} | |
def main(args: Array[String]) { | |
println(A("bob", 4).toMapRec) | |
// Map(name -> bob, age -> 4) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment