简体   繁体   English

获取Scala中的所有枚举案例对象值

[英]Getting all enum-y case object values in Scala

In Scala, enums are a disputed area and many people (including myself) rather use case object s than any library-based enumeration. 在Scala中,枚举是一个有争议的领域,许多人(包括我自己)比任何基于库的枚举都使用case object 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. 我手动维护了这些列表( allKeys ),但这很乏味且容易出错。

The question is: how can Scala 2.11 TypeTags or reflection be used, to create such a list? 问题是:如何使用Scala 2.11 TypeTags或反射来创建这样的列表?

One of two ways would work: 两种方法之一可行:

  • getting all derived instances of a sealed class 获取sealed类的所有派生实例
  • getting all case object s declared within a particular object 获取在特定对象中声明的所有case 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? 我怎么能实现allOf功能?

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. 我试图从Scala文档中获取这些信息,但是当涉及到反射时,事情真的很抽象。 I believe the above need is (should be) covered by Scala 2.11. 我相信上述需求(应该)由Scala 2.11涵盖。

References: 参考文献:

我找到了治疗方法 ,名为Enumeratum,但我认为无论如何我都会发布这个问题,以便人们更容易找到这件新的宏观珠宝。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM