How to iterate all the product types in a coproduct using shapeless?

前端 未结 1 685

Let\'s say I have a coproduct (a sealed trait) such as

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


        
相关标签:
1条回答
  • 2021-02-08 15:08

    For the example use case in your question, this is actually very straightforward:

    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'm using a Set since the order you're getting is just alphabetical—it's not currently possible to enumerate the constructors in declaration order, although I'd personally prefer that.)

    If you'd like a more generic answer, an adaptation of the code in the question I linked above shouldn't be too bad—I'd be happy to add it here later.

    0 讨论(0)
提交回复
热议问题