Quantcast
Channel: How do I create an enum from an Int in Kotlin? - Stack Overflow
Viewing all articles
Browse latest Browse all 13

Answer by Zoe - Save the data dump for How do I create an enum from an Int in Kotlin?

$
0
0

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.

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.

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() 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.

Admittedly, and as discussed in the comments, this may be an insignificant optimization, depending on your use. This means you can also do:

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

if that's something you'd prefer for readability or some other reason.

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.


Viewing all articles
Browse latest Browse all 13

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>