4

I have an enum like this:

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

and I need to pick at random an element from this enumeration. How can i efficiently do this in scala?

Luka Jacobowitz
  • 22,795
  • 5
  • 39
  • 57
lads
  • 1,125
  • 3
  • 15
  • 29

1 Answers1

6

Less than a minute with the documentation shows

final def maxId: Int

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

and

final def apply(x: Int): Value

The value of this enumeration with given id x

So

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

(assuming all values are used, and you didn't pass in an initial value to the constructor)

Or you could enumerate the values with Animals.values and then refer to this question

Community
  • 1
  • 1
The Archetypal Paul
  • 41,321
  • 20
  • 104
  • 134