Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Random Choice element from Enum Scala3

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.

like image 774
olimath Avatar asked Nov 21 '21 17:11

olimath


People also ask

What is enum Scala?

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.


Video Answer


2 Answers

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)
like image 174
Kolmar Avatar answered Oct 20 '22 14:10

Kolmar


enum Colors:
  case Blue, Red, Green

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

  val mycolor = Colors.values

  println(Random.shuffle(mycolor).head)

like image 35
olimath Avatar answered Oct 20 '22 13:10

olimath