Skip to content

Instantly share code, notes, and snippets.

@franklinchou
Forked from milessabin/gist:9042788
Created November 23, 2018 00:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save franklinchou/9d27a92c3cb9537146a16ffe1ba55799 to your computer and use it in GitHub Desktop.
Save franklinchou/9d27a92c3cb9537146a16ffe1ba55799 to your computer and use it in GitHub Desktop.
Boilerplate free conversion from case classes to shapeless records via LabelledGeneric ... coming soon to shapeless 2.0.0.
scala> import shapeless._, record._
import shapeless._
import record._
scala> case class Person(name: String, address: String, age: Int)
defined class Person
scala> val joe = Person("Joe", "Brighton", 33)
joe: Person = Person(Joe,Brighton,33)
scala> val gen = LabelledGeneric[Person]
gen: shapeless.LabelledGeneric[Person]{type Repr = shapeless.::[shapeless.record.FieldType[shapeless.tag.@@[Symbol,String("name")],String],shapeless.::[shapeless.record.FieldType[shapeless.tag.@@[Symbol,String("address")],String],shapeless.::[shapeless.record.FieldType[shapeless.tag.@@[Symbol,String("age")],Int],shapeless.HNil]]]} = $1$$1@19dbafd7
scala> val joeRecord = gen.to(joe)
joeRecord: gen.Repr = Joe :: Brighton :: 33 :: HNil
scala> joeRecord.keys
res0: shapeless.::[shapeless.tag.@@[Symbol,String("name")],shapeless.::[shapeless.tag.@@[Symbol,String("address")],shapeless.::[shapeless.tag.@@[Symbol,String("age")],shapeless.HNil]]] = 'name :: 'address :: 'age :: HNil
scala> joeRecord.values
res1: shapeless.::[String,shapeless.::[String,shapeless.::[Int,shapeless.HNil]]] = Joe :: Brighton :: 33 :: HNil
scala> joeRecord('name)
res2: String = Joe
scala> joeRecord('address)
res3: String = Brighton
scala> joeRecord('age)
res4: Int = 33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment