Hey, welcome again to my blog! Today, we shall learn more about Kotlin Enum Classes and if you have missed any of my previous tutorials in this series, kindly check them out here.
We learnt about sealed classes in the previous blog.
In programming, sometimes there arises a need for a type to have only certain values. To accomplish this, the concept of enumeration was introduced. Enumeration is a named list of constants.
What are Enum
Classes?
An Enum
is a special "class" that represents a group of constants (unchangeable variables, like final variables).
In Kotlin, like many other programming languages, an enum has its own specialized type, indicating that something has a number of possible values.
Initializing enums
enum class Day { }
As you can see, the enum
keyword is followed by the class
keyword. This should prevent you from being fooled into thinking that Kotlin enums are mere types.
Kotlin enums are much more than that. They can use anonymous classes and implement interfaces, just like any other Kotlin class.
Example:
enum class Day {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
Kotlin enums are classes, which means that they can have one or more constructors. Thus, you can initialize enum constants by passing the values required to one of the valid constructors.
enum class Day(val dayOfWeek: Int) {
MONDAY(1),
TUESDAY(2),
WEDNESDAY(3),
THURSDAY(4),
FRIDAY(5),
SATURDAY(6),
SUNDAY(7)
}
This is possible because enum
constants are nothing other than instances of the enum class itself.
Another example to fully demonstrate enum class in Kotlin:
enum class DAYS {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}
fun main()
{
// A simple demonstration of properties and methods
for (day in DAYS.values()) {
println("${day.ordinal} = ${day.name}")
}
println("${DAYS.valueOf(" WEDNESDAY ")}")
}
As we can see from the code above: we have seen some methods and properties used. Let me explain them shortly;
Properties –
🔹 ordinal
: This property stores the ordinal value of the constant, which is usually a zero-based index.
🔹 name
: This property stores the name of the constant.
Methods –
🔹 values
: This method returns a list of all the constants defined within the enum class
.
🔹 valueOf
: This method returns the enum
constant defined in enum
, matching the input string. If the constant, is not present in the enum
, then an IllegalArgumentException is thrown.
Enums as Anonymous Classes –
Enum
constants also behave as anonymous classes by implementing their own functions along with overriding the abstract functions of the class. The most important thing is that each enum
constant must be overridden.
// defining enum class
enum class Seasons(var weather: String) {
Summer("hot"){
// compile time error if not override the function foo()
override fun foo() {
println("Hot days of a year")
}
},
Winter("cold"){
override fun foo() {
println("Cold days of a year")
}
},
Rainy("moderate"){
override fun foo() {
println("Rainy days of a year")
}
};
abstract fun foo()
}
// main function
fun main(args: Array<String>) {
// calling foo() function override be Summer constant
Seasons.Summer.foo()
}
Usage of when expression with enum class –
A great advantage of enum classes in Kotlin comes into play when they are combined with the when
expression.
The advantage is since enum
classes restrict the value a type can take, so when used with the when expression and the definition for all the constants are provided, then the need of the else
clause is completely eliminated. In fact, doing so will generate a warning from the compiler.
enum class DAYS{
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;
}
fun main(){
when(DAYS.FRIDAY){
DAYS.SUNDAY -> println("Today is Sunday")
DAYS.MONDAY -> println("Today is Monday")
DAYS.TUESDAY -> println("Today is Tuesday")
DAYS.WEDNESDAY -> println("Today is Wednesday")
DAYS.THURSDAY -> println("Today is Thursday")
DAYS.FRIDAY -> println("Today is Friday")
DAYS.SATURDAY -> println("Today is Saturday")
// Adding an else clause will generate a warning
}
}
Output:
Today is Friday
Python Enum
Enumerations in Python are implemented by using the module named “enum“.Enumerations are created using classes. Enums have names and values associated with them.
Just pip install enum
import enum
# creating enumerations using class
class Days(enum.Enum):
SUNDAY=0
MONDAY=1
TUESDAY=2
WEDNESDAY=3
THURSDAY=4
FRIDAY=5
SATURDAY=6
# printing enum member as string
print ("The string representation of enum member is : ",end="")
print (Days.MONDAY)
# printing enum member as repr
print ("The repr representation of enum member is : ",end="")
print (repr(Days.MONDAY))
# printing the type of enum member using type()
print ("The type of enum member is : ",end ="")
print (type(Days.MONDAY))
# printing name of enum member using "name" keyword
print ("The name of enum member is : ",end ="")
print (Days.MONDAY.name)
The Output:
The string representation of enum member is : Days.MONDAY
The repr representation of enum member is : <Days.MONDAY: 1>
The type of enum member is : <enum 'Days'>
The name of enum member is : MONDAY
Read More Here:
🔸 Log Rocket
🔸 Kotlin Official Docs
🔸 Geeks For Geeks
🔸 Baeldung
🔸 Python Enum
I used some of the code snippets from the Geeks For Geeks site.
If you enjoyed reading, consider subscribing and reacting to this with love by sharing, commenting and any criticism is much welcome.
🔹Follow me on Twitter :
Ronnie Atuhaire 🤓