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

74 Views Asked by At

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
2

There are 2 best solutions below

0
Sweeper On BEST ANSWER

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"
    }
0
Adam Millerchip On

Rather than enumerating the enum values in a function with when, you could consider storing the price as a property of the class:

enum class Tariff(val price: String) {
    STANDARD("1.99"), EVENT("1.49"), WEEKEND("2.99");
}

Then you can call it like this:

fun main() {
    println(Tariff.STANDARD.price)
    println(Tariff.EVENT.price)
    println(Tariff.WEEKEND.price)
}

Result:

1.99
1.49
2.99