Kotlin:在when时使用枚举 [英] Kotlin: Using enums with when

查看:334
本文介绍了Kotlin:在when时使用枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以将枚举的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"
   }
}

上面的示例将不起作用,因为x是int且提供的值是枚举,如果我按PaymentStatus.PAID.value进行操作,它将起作用,但随后的时间(完全覆盖)和

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)

不起作用.

有人有什么想法可以完成这项工作吗?

Any one have any ideas to make this work?

推荐答案

如果需要检查值,可以执行以下操作:

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()
    }
}

或者您可以在枚举类的伴侣对象中创建工厂方法create:

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"
    }
}

这篇关于Kotlin:在when时使用枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆