Skip to content

Instantly share code, notes, and snippets.

@ahoy-jon
Created August 20, 2015 14:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahoy-jon/b9e0cdf837858efa287f to your computer and use it in GitHub Desktop.
Save ahoy-jon/b9e0cdf837858efa287f to your computer and use it in GitHub Desktop.
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