Enum in Kotlin is a way to define a set of constant values. Enums are very useful, but not limited, as configuration values:
enum class Flour {
WHEAT, CORN, CASSAVA
}
Each element is an object that extends the Flour class.
Like any object, they can extend interfaces:
interface Exotic {
fun isExotic(): Boolean
}
enum class Flour : Exotic {
WHEAT {
override fun isExotic(): Boolean {
return false
}
},
CORN {
override fun isExotic(): Boolean {
return false
}
},
CASSAVA {
override fun isExotic(): Boolean {
return true
}
}
}
Enum can also have abstract methods:
enum class Flour: Exotic {
WHEAT {
override fun isGlutenFree(): Boolean {
return false
}
override fun isExotic(): Boolean {
return false
}
},
CORN {
override fun isGlutenFree(): Boolean {
return true
}
override fun isExotic(): Boolean {
return false
}
},
CASSAVA {
override fun isGlutenFree(): Boolean {
return true
}
override fun isExotic(): Boolean {
return true
}
};
abstract fun isGlutenFree(): Boolean
}
Any method definition must be declared after the (;) separating the last element.
When enums are used with when expressions, Kotlin's compiler checks that all cases are covered (individually or with an else):
fun flourDescription(flour: Flour): String {
return when(flour) { // error
Flour.CASSAVA -> "A very exotic flavour"
}
}
In this case, we're only checking for CASSAVA and not the other elements; therefore, it fails:
fun flourDescription(flour: Flour): String {
return when(flour) {
Flour.CASSAVA -> "A very exotic flavour"
else -> "Boring"
}
}