如何从 Kotlin 中的 Int 创建枚举? [英] How do I create an enum from an Int in Kotlin?

查看:31
本文介绍了如何从 Kotlin 中的 Int 创建枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个enum:

enum class Types(val value: Int) {
    FOO(1)
    BAR(2)
    FOO_BAR(3)
}

如何使用 Int 创建该 enum 的实例?

How do I create an instance of that enum using an Int?

我尝试做这样的事情:

val type = Types.valueOf(1)

然后我得到错误:

整数字面量不符合预期的字符串类型

Integer literal does not conform to the expected type String

推荐答案

Enum#valueOf 基于名字.这意味着为了使用它,您需要使用 valueof("FOO").valueof 方法因此需要一个字符串,它解释了错误.String 不是 Int,类型很重要.我也提到它的作用是为了让您知道这不是您要寻找的方法.

Enum#valueOf is based on name. Which means in order to use that, you'd need to use valueof("FOO"). The valueof method consequently takes a String, which explains the error. A String isn't an Int, and types matter. The reason I mentioned what it does too, is so you know this isn't the method you're looking for.

如果你想根据一个 int 值抓取一个,你需要定义你自己的函数来做到这一点.您可以使用 values() 获取枚举中的值,在这种情况下,它返回 Array.您可以使用 firstOrNull 作为一种安全的方法,或者 first 如果您更喜欢异常而不是 null.

If you want to grab one based on an int value, you need to define your own function to do so. You can get the values in an enum using values(), which returns an Array<Types> in this case. You can use firstOrNull as a safe approach, or first if you prefer an exception over null.

所以添加一个伴随对象(相对于枚举是静态的,所以你可以调用 Types.getByValue(1234) (Types.COMPANION.getByValue(1234)来自 Java) 超过 Types.FOO.getByValue(1234).

So add a companion object (which are static relative to the enum, so you can call Types.getByValue(1234) (Types.COMPANION.getByValue(1234) from Java) over Types.FOO.getByValue(1234).

companion object {
    private val VALUES = values()
    fun getByValue(value: Int) = VALUES.firstOrNull { it.value == value }
}

values() 每次调用时都会返回一个新数组,这意味着您应该在本地缓存它以避免每次调用 getByValue 时都重新创建一个.如果在调用方法时调用 values(),则可能会重复重新创建它(具体取决于您实际调用它的次数),这会浪费内存.

values() returns a new Array every time it's called, which means you should cache it locally to avoid re-creating one every single time you call getByValue. If you call values() when the method is called, you risk re-creating it repeatedly (depending on how many times you actually call it though), which is a waste of memory.

该函数还可以根据多个参数进行扩展和检查,如果这是您想做的事情.这些类型的函数不限于一个参数.

The function could also be expanded and check based on multiple parameters, if that's something you want to do. These types of functions aren't limited to one argument.

函数的命名完全取决于你.它不一定是 getByValue.

这篇关于如何从 Kotlin 中的 Int 创建枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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