我有一个这样的枚举:
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/