14

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. However, it seems I can't use its value to retrieve the element.

3
  • 1
    Try answers[n].text
    – Enzokie
    May 29, 2018 at 10:46
  • Thanks, I forgot the property declaration. So it keeps telling me unresolved text
    – sfy
    May 29, 2018 at 10:59
  • Yeah you're right, I did not notice the missing val.
    – Enzokie
    May 29, 2018 at 11:01

6 Answers 6

18

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)
3
  • 4
    Note: this is actually not the best solution performance-wise as it allocates a separate list and processes all the items of the original array, which is not necessary if you only need a single random item. Don't use it in performance-critical code.
    – hotkey
    May 29, 2018 at 10:54
  • 1
    @hotkey fully agree - I will expand the answer May 29, 2018 at 10:55
  • 1
    Thanks, I forgot that surely, this solution is enlightening.
    – sfy
    May 29, 2018 at 11:01
13

Answer.values().random() will do the job for you in Kotlin.

1

When you write val/var within the constructor for a param, it declares a property inside the class. When you do not write it, it is simply a parameter passed to the primary constructor. So just add val to the constructor param text which will make it a property with a getter and above program will work..

import java.util.*

class Answers {
    enum class Answer(val text: String) {
        YES("Yes."),
        No("No."),
        MAYBE("Maybe."),
        AGAIN("Ask again.")
    }
    val answers: Array<Answer> = Answer.values()
    val rand = Random()

    fun genAnswer ():String {
        val n = rand.nextInt(3)+1
        return answers[n].text
    }
}

fun main(String: Array<String>) {
    print(Answers().genAnswer())
}
0

I use this generic functions for any type of enum

/**
 * return random enum value of enum class T
 */
inline fun <reified T : Enum<T>> randomEnum(): T {
    val enumValues: Array<T> = enumValues()
    return enumValues[(0 until enumValues.size).random()]
}

/**
 * return random Int from start to end of range
 */
fun IntRange.random(): Int =
    Random().nextInt((endInclusive + 1) - start) + start
0

I had a Enum SupportedLocale with values for languages

I did it in 2 steps

Get a list of values for enum:

  val languages: Array<SupportedLocale> = SupportedLocale.values()

Now select random value using ordinate position

 val randomLocale = languages[Random().nextInt(languages.size)]
0

An easy solution that I have used is

enum class OPERATOR(val symbol:String){MULTIPLY("*"),DIVIDE("/"),ADD("+"),SUBTRACT("-"),REMINDER("-")}

private fun getRandomOperator():String{
        val limit=OPERATOR.values().size-1
        return OPERATOR.values()[IntRange(0,limit).random()].symbol
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.