Is there a builtin way to get the number of items of an Enum with something like Myenum.length
,
Or do I have to implement myself a function int size()
hardcording the number of element?
Is there a builtin way to get the number of items of an Enum with something like Myenum.length
,
Or do I have to implement myself a function int size()
hardcording the number of element?
You can get the length by using Myenum.values().length
The Enum.values()
returns an array of all the enum
constants. You can use the length
variable of this array to get the number of enum
constants.
Assuming you have the following enum:
public enum Color
{
BLACK,WHITE,BLUE,GREEN,RED
}
The following statement will assign 5 to size
:
int size = Color.values().length;
I searched for a Kotlin answer and this question popped up. So, here is my answer.
enum class MyEnum { RED, GREEN, BLUE }
MyEnum.values().size // 3
This is another way to do it:
inline fun <reified T : Enum<T>> sizeOf() = enumValues<T>().size
sizeOf<MyEnum>() // 3
Thanks to this answer.