Created
February 17, 2014 00:42
-
-
Save milessabin/9042788 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.
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
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
I would like to read the field name from a list. Such as;
val list = List('name, 'address, 'age)
list.map(x => lens[Person] >> x)
Is it possible?
Because I try to do this, and getting error. I also asked a similar question here. https://stackoverflow.com/questions/50418767/shapeless-lenses-usage-with-a-string-definition