Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get an random element from an enum class in kotlin?

Tags:

kotlin

Like the title says

class Answers {
    enum class Answer(text: String) {
        YES("Yes."),
        No("No."),
        MAYBE("Maybe."),
        AGAIN("Ask again.")
    }
    val answers = Answer.values()
    val rand = Random()
    fun genAnswer ():String {
        val n = rand.nextInt(3)+1
//        return Answer[answers[n]].text
    }
}

I want to pick an enum element randomly and return its text property, but it seems I can't use its value to retrieve the element.

I think the info is sufficient.

like image 488
wolfrevo Avatar asked May 29 '18 10:05

wolfrevo


2 Answers

You can get a random enum value by doing:

val randomAnswer = Answer.values().toList().shuffled().first().text

Keep in mind that it goes for convenience over performance.


Remember to expose the text property with val. For now, it's just a constructor param:

enum class Answer(val text: String)
like image 134
Grzegorz Piwowarek Avatar answered Sep 19 '22 12:09

Grzegorz Piwowarek


Answer.values().random() Should do the job for kotlin.

like image 25
Pulkit Avatar answered Sep 20 '22 12:09

Pulkit