kotlinenumskotlin-when

Kotlin: Using enums with when


Is there any way to cast a when argument to an enum?

 enum class PaymentStatus(val value: Int) {
     PAID(1),
     UNPAID(2) 
 }

fun f(x: Int) {
   val foo = when (x) {
     PaymentStatus.PAID -> "PAID"
     PaymentStatus.UNPAID -> "UNPAID"
   }
}

The above example will not work, as x is int and the values provided are the enum, if I go by PaymentStatus.PAID.value it would work but then I don't get the benefit of when (full coverage), and

when (x as PaymentStatus)

does not work.

Any one have any ideas to make this work?


Solution

  • If you need to check a value you can do something like this:

    fun f(x: Int) {
        val foo = when (x) {
            PaymentStatus.PAID.value -> "PAID"
            PaymentStatus.UNPAID.value -> "UNPAID"
    
            else -> throw IllegalStateException()
        }
    }
    

    Or you can create factory method create in the companion object of enum class:

    enum class PaymentStatus(val value: Int) {
        PAID(1),
        UNPAID(2);
    
        companion object {
            fun create(x: Int): PaymentStatus {
                return when (x) {
                    1 -> PAID
                    2 -> UNPAID
                    else -> throw IllegalStateException()
                }
            }
        }
    }
    
    fun f(x: Int) {
        val foo = when (PaymentStatus.create(x)) {
            PaymentStatus.PAID -> "PAID"
            PaymentStatus.UNPAID -> "UNPAID"
        }
    }