Scala 对象反射

发布于 2024-12-11 02:28:06 字数 365 浏览 0 评论 0原文

如果我有以下 scala 对象:

object CustomerState {
   val PENDING = "pending"
   val TRIAL = "trial"
   val PAYING = "paying"
   val DEACTIVATED_TRIAL = "deactivated_trial"
   val DEACTIVATED_PAYING = "deactivated_paying"
}

如何获取所有 val 值的列表?在这种情况下,我希望获得一个列表(“待处理”、“试用”、“正在支付”、“deactivated_trial”、“deactivated_pa​​ying”)

提前致谢, 托德

If I have the following scala object:

object CustomerState {
   val PENDING = "pending"
   val TRIAL = "trial"
   val PAYING = "paying"
   val DEACTIVATED_TRIAL = "deactivated_trial"
   val DEACTIVATED_PAYING = "deactivated_paying"
}

How can I obtain a list of all the val values? In this case, I'm looking to get a List of ("pending", "trial", "paying", "deactivated_trial", "deactivated_paying")

Thanks in advance,
Todd

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

余罪 2024-12-18 02:28:06

目前我认为你能做的最好的事情就是获取所有零参数方法的列表(因为这就是 val 被编译成的)并调用它们:

CustomerState.getClass.getMethods.toList.filter(_.getParameterTypes.isEmpty).map(_.invoke(CustomerState))

将会有一个 Scala- 2.10 中特定的反射库,这将使事情变得更好。

At the moment I think the best you can do is to get a list of all zero-argument methods (since that's what vals are compiled to) and call them:

CustomerState.getClass.getMethods.toList.filter(_.getParameterTypes.isEmpty).map(_.invoke(CustomerState))

There is going to be a Scala-specific reflection library in 2.10, which will make things better.

吻安 2024-12-18 02:28:06

您不应该使用 Enumeration?

例子:

object Main extends Application {

   object CustomerState extends Enumeration {
     type CustomerState = Value
     val Pending, Trial, Paying, Deactivated = Value
   }

   import CustomerState._

   CustomerState.values foreach println // Will print each value
 }

Shouldn't you be using an Enumeration?

Example:

object Main extends Application {

   object CustomerState extends Enumeration {
     type CustomerState = Value
     val Pending, Trial, Paying, Deactivated = Value
   }

   import CustomerState._

   CustomerState.values foreach println // Will print each value
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文