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

查看:847
本文介绍了如何从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,它解释了该错误.字符串不是整数.类型很重要.我之所以也提到它的原因是,所以您知道这不是您要寻找的方法.

Enum#valueOf is based on name. Which means in order to use that, you'd need to use valueof("FOO"). The valueof method also takes a String, which explains the error. A String isn't an Int; 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<Types>.您可以使用firstOrNull作为一种安全的方法,如果您希望使用异常而不是null,则可以使用first.

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.FOO.getByValue(1234)上调用Types.getByValue(1234)(从Java中是Types.COMPANION.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天全站免登陆