有没有办法将 when 参数转换为枚举?
enum class PaymentStatus(val value: Int) {
PAID(1),
UNPAID(2)
}
fun f(x: Int) {
val foo = when (x) {
PaymentStatus.PAID -> "PAID"
PaymentStatus.UNPAID -> "UNPAID"
}
}
Run Code Online (Sandbox Code Playgroud)
上面的例子不起作用,因为 x 是 int 并且提供的值是枚举,如果我去PaymentStatus.PAID.value
它会起作用,但是我没有得到什么时候(完全覆盖)的好处,并且
when (x as PaymentStatus)
Run Code Online (Sandbox Code Playgroud)
不起作用。
任何人有任何想法使这项工作?
Ser*_*gey 13
如果您需要检查一个值,您可以执行以下操作:
fun f(x: Int) {
val foo = when (x) {
PaymentStatus.PAID.value -> "PAID"
PaymentStatus.UNPAID.value -> "UNPAID"
else -> throw IllegalStateException()
}
}
Run Code Online (Sandbox Code Playgroud)
或者您可以create
在枚举类的伴随对象中创建工厂方法:
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"
}
}
Run Code Online (Sandbox Code Playgroud)
when
在这个特定的用例中你不需要。
enum
由于您的目标是获取具有特定值的元素的名称x
,因此您可以迭代PaymentStatus
类似的元素并使用以下方法选择匹配的元素firstOrNull
:
fun getStatusWithValue(x: Int) = PaymentStatus.values().firstOrNull {
it.value == x
}?.toString()
println(getStatusWithValue(2)) // "UNPAID"
Run Code Online (Sandbox Code Playgroud)
调用toString()
一个enum
元素将返回它的名称。
编辑:由于您不希望在添加新代码时编译代码PaymentStatus
,因此您可以使用详尽的when
:
fun paymentStatusNumToString(x: Int): String {
val status = PaymentStatus.values().first { it.value == x }
// when must be exhaustive here, because we don't use an else branch
return when(status) {
PaymentStatus.PAID -> "PAID" // you could use status.toString() here too
PaymentStatus.UNPAID -> "UNPAID"
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9759 次 |
最近记录: |