scala - 如何有效地从scala的枚举中选择一个随机元素?

标签 scala random enums

我有一个这样的枚举:

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

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

最佳答案

documentation 不到一分钟显示
final def maxId: Int

The one higher than the highest integer amongst those used to identify values in this enumeration.




final def apply(x: Int): Value

The value of this enumeration with given id x



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

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

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

关于scala - 如何有效地从scala的枚举中选择一个随机元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36386610/

相关文章:

scala - 如何让测试在 Scalatest 中始终以相同的顺序运行?

scala - Scala 中的隐式类

r - 生成彩票号码的循环

java - 可以在 @Value 中使用 Enum

scala - akka 分片代理无法与协调器联系

scala - 使用 Slick 重构期间的类型不匹配

python - 在 python 中获取 1 到 100 万之间的随机数的最快方法

c++ - 在一定范围内随机,新 rand() 版本是否存在数字偏差?

java - 当字符串包含破折号时打开枚举

java - 是否可以在 Groovy 中提供自己类型的 Enums 实例变量?