kotlinenumscase-when

How can I get a method working with "when" inside a enum class?


I need this "fun price" method working with the WHEN call. However, I just can't get it done. I need to be able to print out the commented code down below. What am I missing?

enum class Tariff {
   STANDARD, EVENT, WEEKEND;

   fun price() {
       when {
           STANDARD -> "1.99"
           EVENT -> "1.49"
           WEEKEND -> "2.99"

       }
   }
}

//val  default = Tariff.STANDARD
//println(default.price()) // gives 1.99
//val weekend  = Tariff.WEEKEND
//println(weekend.price()) // gives 2.99

Solution

  • To refer to the thing (the instance of the enum) on which price() is called inside the enum, you use the word this, so you should do:

    fun price() : String {
        return when (this) {
            STANDARD -> "1.99"
            EVENT -> "1.49"
            WEEKEND -> "2.99"
        }
    }
    

    Note the return type and return keyword.

    Or:

    fun price() =
        when (this) {
            STANDARD -> "1.99"
            EVENT -> "1.49"
            WEEKEND -> "2.99"
        }