I'm learning shapeless and referring a tutorial from here. Which says,
Generic is a simple way to convert case class and product types (like tuples) to HList, and vice-versa:
import shapeless.Generic
case class UserWithAge(name: String, age: Int)
val gen = Generic[UserWithAge]
val u = UserWithAge("Julien", 30)
val h = gen.to(u)
Now if I print h
, I will get Julien :: 30 :: HNil
. But, I'm unable to read each element from h
such as h.head
, h.tail
will not work and there aren't any methods available in h
. Here, h
is type of gen.Repr
and I couldn't figure out a way to convert it into HList
either. So, how can I read each element from h
?
In this case the type of gen.to(u)
is gen.Repr
, which if you look at the type of gen
actually expends to String :: Int :: HNil
, so it's already a HList
!
scala> import shapeless.Generic
import shapeless.Generic
scala> case class UserWithAge(name: String, age: Int)
defined class UserWithAge
scala> val gen = Generic[UserWithAge]
gen: shapeless.Generic[UserWithAge]{type Repr = shapeless.::[String,shapeless.::[Int,shapeless.HNil]]} = anon$macro$3$1@4ff329b8
scala> val u = UserWithAge("Julien", 30)
u: UserWithAge = UserWithAge(Julien,30)
scala> val h = gen.to(u)
h: gen.Repr = Julien :: 30 :: HNil
scala> h.head
res0: String = Julien
scala> h.tail
res1: shapeless.::[Int,shapeless.HNil] = 30 :: HNil
In the general case, the Repr
type of a Generic
will be either a HList
or a Coproduct
. For examples of how to generically program over these, see shapeless-type-class-derivation-2015-demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With