Home > front end >  How to Random Choice element from Enum Scala3
How to Random Choice element from Enum Scala3

Time:11-23

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.

CodePudding user response:

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)

CodePudding user response:

enum Colors:
  case Blue, Red, Green

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

  val mycolor = Colors.values

  println(Random.shuffle(mycolor).head)

  • Related