In Scala, enums are a disputed area and many people (including myself) rather use case object
s 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:
sealed
classcase object
s declared within a particular objectNote: 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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With