Issue
I have this enum
:
enum class Types(val value: Int) {
FOO(1)
BAR(2)
FOO_BAR(3)
}
How do I create an instance of that enum
using an Int
?
I tried doing something like this:
val type = Types.valueOf(1)
And I get the error:
Integer literal does not conform to the expected type String
Solution
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.
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.
Naming of the function is entirely up to you though. It doesn't have to be getByValue
.
Answered By - Zoe
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.