Q:
How do I use Kotlin to type check an enum type?
I am trying to write a function that takes an Enum type and returns the integer that is listed in the enum.
For example, this works:
fun sumOfEnum(enum: MyEnum): Int {
for (e in enum) {
when (e) {
MyEnum.ZERO -> return 0
MyEnum.ONE -> return 1
MyEnum.TWO -> return 2
}
}
}
But I want to make this function type-safe, so that it doesn't compile if someone uses the function on an enum that isn't defined in the enumeration.
I tried using the? syntax to try to make this work:
fun sumOfEnum(enum: MyEnum?): Int {
for (e in enum) {
when (e) {
MyEnum.ZERO -> return 0
MyEnum.ONE -> return 1
MyEnum.TWO -> return 2
}
}
}
But this causes a compile error:
Type mismatch.
Required:
MyEnum?
Found:
MyEnum
How do I write the function so that it will return a default value if the enum isn't defined in the enumeration?
A:
You can use one of these two approaches:
Use a common base type for your enum values, say Int, and create a function sumOfEnum2(enum: MyEnum2): Int that sums all values of an enum whose type extends MyEnum2.
Create a map of enum values to their values, using the values of MyEnum. Then create a function sumOfEnum3(enum: MyEnum): Int that sums all values of enum that are mapped to a specific value, as defined in the Enum ac619d1d87
Related links:
Comments