【问题标题】:How to efficiently pick a random element from an enumeration in scala?如何有效地从scala的枚举中选择一个随机元素?
【发布时间】:2016-04-03 14:24:15
【问题描述】:

我有一个这样的枚举:

object Animals extends Enumeration {
  type Animals = Value
  val Monkey = Value("Monkey")
  val Lion = Value("Lion")
  val Dog = Value("Dog")
  val Cat = Value("Cat")
}

我需要从这个枚举中随机选择一个元素。我怎样才能在 scala 中有效地做到这一点?

【问题讨论】:

    标签: scala random enums


    【解决方案1】:

    documentation 节目不到一分钟

    final def maxId: Int

    大于用于标识此枚举中的值的整数中的最高整数。

    final def apply(x: Int): Value

    给定 id x 的枚举值

    所以

    Animals(scala.util.Random.nextInt(Animals.maxId))
    //> res0: recursion.recursion.Animals.Value = Monkey
    

    (假设所有值都被使用,并且你没有将初始值传递给构造函数)

    或者您可以使用Animals.values 枚举值,然后参考this question

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-30
      • 2013-10-20
      • 2010-09-08
      • 2011-06-30
      • 2018-07-07
      相关资源
      最近更新 更多