1
votes

I have recently discovered Shapeless and I'm wondering whetherit is possible to do the following with it. Let's say I have this sealed trait and case classes:

sealed trait T

case class C1() extends T
case class C2() extends T

I defined an extensible records of this form:

val myRecords = (C1 ->> SomeObj1) :: (C2 ->> SomeObj2) :: HNil

However, if I have val x = C1(), how can I get SomeObj1 out of myRecords?

I don't want to pattern-match here, and I want to preserve the type information of SomeObj1 and SomeObj2.

Another question is how can I enforce people to extends my trait T with another case class to add a corresponding record to myRecords.

1
I'm not sure you want a record. Polymorphic function seems a better fit: object foo extends Poly1 { implicit def caseC1 = at[C1](_ => SomeObj1) implicit def caseC2 = at[C2](_ => SomeObj2) }Kolmar
@Kolmar: Thanks for your reply. At first I thought of a record because I want to have multiple of records at different places (I have multiple sealed traits) and then combine them together. I am not sure how to do it with Polymorphic functions.hosyvietanh

1 Answers

0
votes

You simply use the apply method that comes predefined on myRecords.

import shapeless._ ; import syntax.singleton._ ; import record._

val x: C1 = ...
val myRecords = (x ->> SomeObj1) :: (C2 ->> SomeObj2) :: HNil
val pair = myRecords(x)