My problem is very simple. I have the following:
enum Colors:
case Blue, Red, Green
How can I choose a random element from this enum? I tried the solution from this question but it didn't work.
Scala provides an Enumeration class which we can extend in order to create our enumerations. Every Enumeration constant represents an object of type Enumeration. Enumeration values are defined as val members of the evaluation. When we extended the Enumeration class, a lot of functions get inherited.
You can use Random.nextInt
to generate an index of a random enum value.
This avoids shuffling the Array
of values, and generates only one random number.
import scala.util.Random
enum Colors:
case Blue, Red, Green
object Colors:
private final val colors = Colors.values
def random: Colors = colors(Random.nextInt(colors.size))
@main def run: Unit =
println(Colors.random)
enum Colors:
case Blue, Red, Green
@main def run: Unit =
import scala.util.Random
val mycolor = Colors.values
println(Random.shuffle(mycolor).head)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With