Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.