Kotlin Enum Class
24. Kotlin Enum Class
24.1 Enum
24.2 Kotlin Enum Anonymous Class
24.3 Kotlin Enum Inside Enum
Enum
Enum stands for enumeration, it is a special type of class. This is used to set some predefined constants. The enum keyword is used to create an enumeration class.
In the given example, we have created enum class of all the days in a week.
enum class Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY}
In the above example, each enum constants is an object and separated with commas.
Kotlin Enum Anonymous Class
In Kotlin, each enum constant can have anonymous class.
enum class Days(val days: String) {
MONDAY("MON") {
override fun printdata() {
println("First Working Day")
}
},
TUESDAY("TUE") {
override fun printdata() {
println("Second Working Day")
}
},
SATURDAY("SAT") {
override fun printdata() {
println("First Weekend")
}
},
SUNDAY("SUN") {
override fun printdata() {
println("Last Weekend")
}
};
abstract fun printdata()
}
fun main(args : Array<String>) {
Days.TUESDAY.printdata()
println(Days.TUESDAY)
}
Output
Second Working Day
TUESDAY
In the above example, we have created four enum constants and override printdata() function within it.
Kotlin Enum Inside Enum
In Kotlin, we can write one enum class inside another enum class.
enum class Zone(val zone: String) {
East("E"),
West("W"),
North("N"),
South("S");
enum class EastZone(val Country: String){
China("China"),
India("India"),
Nepal("Nepal")
}
}
fun main(args : Array<String>) {
println(Zone.EastZone.China)
}
Output
China
In the above example, we have created a EastZone enum class inside the Zone enum class.