5

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.

Peter O.
  • 30,765
  • 14
  • 76
  • 91
olimath
  • 71
  • 4

2 Answers2

3

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)
Kolmar
  • 13,842
  • 1
  • 21
  • 24
2
enum Colors:
  case Blue, Red, Green

@main def run: Unit = 
  import scala.util.Random

  val mycolor = Colors.values

  println(Random.shuffle(mycolor).head)

olimath
  • 71
  • 4