问题描述
我正在尝试找到对 Kotlin 中的枚举进行反向查找"的最佳方法.我从 Effective Java 中得到的一个收获是,您在枚举中引入了一个静态映射来处理反向查找.使用一个简单的枚举将其移植到 Kotlin 中,我会得到如下所示的代码:
I'm trying to find the best way to do a 'reverse lookup' on an enum in Kotlin. One of my takeaways from Effective Java was that you introduce a static map inside the enum to handle the reverse lookup. Porting this over to Kotlin with a simple enum leads me to code that looks like this:
enum class Type(val value: Int) {
A(1),
B(2),
C(3);
companion object {
val map: MutableMap<Int, Type> = HashMap()
init {
for (i in Type.values()) {
map[i.value] = i
}
}
fun fromInt(type: Int?): Type? {
return map[type]
}
}
}
我的问题是,这是最好的方法,还是有更好的方法?如果我有几个遵循类似模式的枚举怎么办?Kotlin 有没有办法让这段代码更易于跨枚举重用?
My question is, is this the best way to do this, or is there a better way? What if I have several enums that follow a similar pattern? Is there a way in Kotlin to make this code more re-usable across enums?
推荐答案
首先,fromInt()
的参数应该是一个Int
,而不是一个 内部?
.尝试使用 null 获取 Type
显然会导致 null,并且调用者甚至不应该尝试这样做.Map
也没有理由是可变的.代码可以简化为:
First of all, the argument of fromInt()
should be an Int
, not an Int?
. Trying to get a Type
using null will obviously lead to null, and a caller shouldn't even try doing that. The Map
has also no reason to be mutable. The code can be reduced to:
companion object {
private val map = Type.values().associateBy(Type::value)
fun fromInt(type: Int) = map[type]
}
那个代码太短了,坦率地说,我不确定是否值得尝试找到一个可重用的解决方案.
That code is so short that, frankly, I'm not sure it's worth trying to find a reusable solution.
这篇关于Kotlin 中的有效枚举与反向查找?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!