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.
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)
Answer.values().random()
Should do the job for kotlin.
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