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?
It basically depends on how you want to solve the identification of the appropriate enum value. The rest is probably easy enough.
Here are some variants to solve that:
extension function to
PaymentStatus.Companion
(or integrate the function into thePaymentStatus.Companion
):Usage of it in a
when
:using a generic function for all your enums
with the following usage then:
this variant clearly has the benefit that it can be reused for basically any
enum
where you want to get a value based on some property or propertiesusing
when
to identify the appropriateenum
:same usage as with the first example. However: I wouldn't use this approach except you have a really good reason for it. The reason I wouldn't use it: it requires you to always remember to adapt both, the enum value and its corresponding counterpart in the
fromValue
-function. So you always have to update the values (at least) twice ;-)If you need to check a value you can do something like this:
Or you can create factory method
create
in the companion object of enum class:You don't need
when
in this particular use-case.Since your goal is to get the name of the
enum
element having a specific valuex
, you can iterate over the elements ofPaymentStatus
like that and pick the matching element usingfirstOrNull
:Calling
toString()
on anenum
element will return its name.