Cheetah
Cheetah

Reputation: 14379

Set of instances of sealed case object hierachy

Imagine I have the following:

sealed trait MyEnum

object MyEnum {
  case object Value1 extends MyEnum
  case object Value2 extends MyEnum
  ...
}

I could fairly easily write a macro (its a few lines of code using knownDirectSubclasses) to give me the Set[MyEnum] of the case objects.

I'm sure this must have been solved already - perhaps there is something in Shapeless or Cats that will give me this set without me having to write the macro? - Is there?

Upvotes: 1

Views: 61

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

This can be done with Enumeratum:

import enumeratum._
import scala.collection.immutable

object Test {
  def main(args: Array[String]): Unit = {
    sealed trait MyEnum extends EnumEntry

    object MyEnum extends Enum[MyEnum] {
      case object Value1 extends MyEnum
      case object Value2 extends MyEnum

      override def values: immutable.IndexedSeq[MyEnum] = findValues
    }

    val res: Set[MyEnum] = MyEnum.values.toSet
  }
}

Upvotes: 1

Related Questions