mardi 17 mars 2015

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:







Aucun commentaire:

Enregistrer un commentaire