How to iterate all types of products into a shapeless product?

Say I have a coproduct (sealed trait) like

sealed trait Traity case object Foo extends Traity case class Bar() extends Traity case class Baz() extends Traity 

Using formlessness, I can apply polymorphic functions to specific instances, but what I would like to do is apply a polymorphic function with a zero parameter (no instance) to all products (for example, to case classes and objects). I have no idea what the syntax will look like, but something conceptually like:

 object mypoly extends Poly1 { implicit def traity[T <: Traity] = when[T]( getClass[T].toString ) } iterate[Traity](mypoly) // gives List("Foo", "Bar", "Baz") 

consistent with my goals.

+7
scala shapeless
source share
1 answer

For an example use in your question, this is actually very simple:

 import shapeless._ class NameHelper[A] { def apply[C <: Coproduct, K <: HList]()(implicit gen: LabelledGeneric.Aux[A, C], keys: ops.union.Keys.Aux[C, K], toSet: ops.hlist.ToTraversable.Aux[K, Set, Symbol] ): Set[String] = toSet(keys()).map(_.name) } def names[A] = new NameHelper[A] 

And then:

 scala> names[Traity]() res0: Set[String] = Set(Bar, Baz, Foo) 

(I use Set , since the order you receive is only alphabetical - it is currently not possible to list constructors in the order of declaration, although I personally would prefer this .

If you want a more general answer, adapting the code in the question that I linked above should not be too bad - I would be happy to add it here later.

+14
source share

All Articles