Kotlin有效枚举反向查询? [英] Effective Enums in Kotlin with reverse lookup?

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

问题描述

我试图找到在Kotlin的枚举上进行反向查找的最佳方式。有效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 = 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?

推荐答案

首先, ()应该是Int,而不是Int?尝试使用null来获取类型显然会导致null,并且调用者不应该尝试这样做。地图也没有理由是可变的。代码可以减少到

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有效枚举反向查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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