Skip to content

Instantly share code, notes, and snippets.

@milessabin
Created September 5, 2013 15:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milessabin/6451859 to your computer and use it in GitHub Desktop.
Save milessabin/6451859 to your computer and use it in GitHub Desktop.
Using pattern matching to destructure shapeless records.
scala> import shapeless._, syntax.singleton._, record._
import shapeless._
import syntax.singleton._
import record._
scala> object ->> {
| def unapply[K, V](f: FieldType[K, V])(implicit k: Witness.Aux[K]) = Option((k.value, f: V))
| }
defined module $minus$greater$greater
scala> :paste
// Entering paste mode (ctrl-D to finish)
val book =
("author" ->> "Benjamin Pierce") ::
("title" ->> "Types and Programming Languages") ::
("id" ->> 262162091) ::
("price" ->> 44.11) ::
HNil
// Exiting paste mode, now interpreting.
book: shapeless.::[String with shapeless.record.KeyTag[String("author"),String],shapeless.::[String with shapeless.record.KeyTag[String("title"),String],shapeless.::[Int with shapeless.record.KeyTag[String("id"),Int],shapeless.::[Double with shapeless.record.KeyTag[String("price"),Double],shapeless.HNil]]]] = Benjamin Pierce :: Types and Programming Languages :: 262162091 :: 44.11 :: HNil
scala> val "author" ->> a :: "title" ->> t :: "id" ->> id :: "price" ->> p :: HNil = book
a: String = Benjamin Pierce
t: String = Types and Programming Languages
id: Int = 262162091
p: Double = 44.11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment