Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all enum-y case object values in Scala

In Scala, enums are a disputed area and many people (including myself) rather use case objects than any library-based enumeration. This is great, except for that one doesn't get a list of all possible values, which sometimes is needed. I've maintained such lists (allKeys) manually, but that is tedious and error-prone.

The question is: how can Scala 2.11 TypeTags or reflection be used, to create such a list?

One of two ways would work:

  • getting all derived instances of a sealed class
  • getting all case objects declared within a particular object

Note: There are samples that seem to promise what I'm looking for. But that's overkill - there must be an almost one-liner to get the same?

Below is a test for this. How could I implement the allOf function?

class ManifestToolsTest extends UnitTest {

  behavior of "ManifestTools" {

    sealed class MyEnum

    object MyEnum {
      case object A extends MyEnum
      case object B extends MyEnum
      case object C extends MyEnum

      val x= 10           // should not be listed
      def f(x: Int) = x   // should not be listed
    }

    def allOf[T]: Seq[T] = {
      ...  
    }

    it should "be able to list the 'case object' members of an object" in {

      val tmp: Seq[MyEnum] = allOf[MyEnum]
      tmp should contain theSameElementsAs( List(MyEnum.A, MyEnum.B, MyEnum.C) )
    }
  }
}

I've tried to get this info from the Scala documentation, but when it comes to reflection, things are really abstract. I believe the above need is (should be) covered by Scala 2.11.

References:

  • Case objects vs Enumerations in Scala
like image 716
akauppi Avatar asked Mar 17 '15 07:03

akauppi


1 Answers

I've found the cure, called Enumeratum, but thought I'd post this question anyhow to make it easier for people to find this new piece of macro jewelry.

like image 140
akauppi Avatar answered Oct 11 '22 21:10

akauppi