Design Converter
Education
Last updated on May 6, 2024
Last updated on Apr 30, 2024
Enum classes in Kotlin serve the purpose of implementing type-safe enums which are somewhat improved from their equivalents in other languages such as Java. This Kotlin Enum blog addresses the topic at length, offering depth and clarity into how Enums work in Kotlin and why they are pivotal tools for any Kotlin developer.
Enum classes in Kotlin not only enhance type safety but also introduce features that align with those found in enums across various programming languages, showcasing their evolution and versatility.
Enums in Kotlin represent a specific type with a limited and definite set of values. For instance, the days of the week, directions like NORTH, SOUTH, EAST, and WEST etc. Here's a basic example of an enum declaration in Kotlin:
1enum class Direction { 2 NORTH, 3 SOUTH, 4 WEST, 5 EAST 6}
Each of these directional values—NORTH, SOUTH, EAST, and WEST—are ‘enums’. They are thus objects of the ‘enum class’ Direction, positioned within their enum declaration.
An Enum class in Kotlin is defined using the enum keyword followed by class, just like you would with a standard class. However, there’s a twist. While each enum is an instance of the enum class, we can initialize it as follows:
1enum class Color(val rgb: Int) { 2 RED(0xFF0000), 3 GREEN(0x00FF00), 4 BLUE(0x0000FF) 5}
In the code snippet above, we declare an enum class named ‘Color’. Within ‘Color’, we define three constants (RED, GREEN, BLUE) with specific values. Each color constant is an object of the enum class type ‘Color’ and is initialized with a specific ‘rgb’ value.
This Kotlin enum example shows how we can pass parameters and properties which gives enums in Kotlin their charm of extensive capability and versatility. It marks the first step towards understanding enum classes better and stands as the tipping point for us to dive deeper into more expansive Kotlin Enum features.
Kotlin Enums are more than mere collections of constants. They can contain properties, methods, and even their anonymous classes. They also have a well-defined class body. In Kotlin, these are called enum classes, highlighting their advanced capabilities such as having properties, methods, and the flexibility to implement interfaces. Let’s delve further into the finer details.
An Enum class can contain property fields just like a regular Kotlin class. You declare these properties within the enum, separating them with a comma and closing with a semicolon. Here's an example of a Kotlin Enum class called ‘Planet’ with a property field 'mass':
1enum class Planet(val mass: Double) { 2 MERCURY(3.303e+23), 3 VENUS(4.869e+24), 4 EARTH(5.976e+24), 5 MARS(6.421e+23), 6 JUPITER(1.9e+27), 7 SATURN(5.688e+26), 8 URANUS(8.686e+25), 9 NEPTUNE(1.024e+26) 10}
In this example, we define a Kotlin Enum called 'Planet' with 'mass' as a value property. We then assign specific values when defining Enum constants.
In this Kotlin enum class, each ‘Planet’ holds a particular ‘mass’ value. Additionally, to enhance functionality similar to static methods in Java, a 'companion object' can be included in an Enum class for defining static functions.
The constants defined in Enum Kotlin classes have well-maintained ordinal values in line with their declaration. Here the ordinal value represents the zero-based index of each enum constant. This concept is crucial for understanding the ordinal and non-ordinal enums, as the ordinal property corresponds to the position of the constant within its enum class declaration. Each Enum constant extends the Enum class, which makes it essential to use ordinal values for comparison and advanced operations.
Here’s an example:
1enum class Color(val rgb: Int) { 2 RED(0xFF0000), 3 GREEN(0x00FF00), 4 BLUE(0x0000FF) 5} 6 7fun main() { 8 val color: Color = Color.RED 9 println(color.ordinal) 10}
This Kotlin enum example declares an enum class ‘Color’. Three enum constants, RED, GREEN, and BLUE, get a zero-based index based on their declaration sequence. So when you print ‘color.ordinal’, the output will be ‘0’ which corresponds to RED's ordinal value.
Notice that, unlike Java enums, Kotlin enums offer advanced features such as the ability to use anonymous classes and implement interfaces, providing more flexibility and functionality in your code. This just skimmed the surface of what is possible with enums in Kotlin. There's still a lot to cover!
The power of Kotlin Enum extends well into assigning values to such Enums to store more complex data. A Kotlin Enum can be initialized with some specific values, enabling developers to work with Enum types that have predefined constants. This feature of passing specific values is quite useful and expands Kotlin's Enum capabilities. Here's an example:
1enum class Planet(val mass: Double, val radius: Double) { 2 MERCURY(3.303e+23, 2.4397e6), 3 VENUS(4.869e+24, 6.0518e6), 4 EARTH(5.976e+24, 6.37814e6), 5 MARS(6.421e+23, 3.3972e6), 6 JUPITER(1.9e+27, 7.1492e7), 7 SATURN(5.688e+26, 6.0268e7), 8 URANUS(8.686e+25, 2.5559e7), 9 NEPTUNE(1.024e+26, 2.4746e7); 10}
In this example, we define a Kotlin Enum called 'Planet' with 'mass' and 'radius' as value properties. Notice how we can pass more than one value when defining Enum constants.
Kotlin enum, with its comprehensive components and inbuilt properties, grants developers the power of finesse and precision. Let's explore the richness of Kotlin enum value.
The power of Kotlin Enum extends to assigning values to Enums to store more complex data. Each Enum constant in a Kotlin Enum extends the Enum class where it is defined and is initialized with some associated value or the default value.
1enum class Signal(val value: String) { 2 WINK("wink"), 3 MOVE_ON("Move On"), 4 STOP("stop"); 5}
Here, we store a string value against each Enum constant of the Enum class 'Signal'.
Kotlin comes with a rich set of string utilities and using String Enum is very straightforward:
1enum class WeekDay(val day: String) { 2 MONDAY("Monday"), 3 TUESDAY("Tuesday"), 4 WEDNESDAY("Wednesday"), 5 THURSDAY("Thursday"), 6 FRIDAY("Friday"), 7 SATURDAY("Saturday"), 8 SUNDAY("Sunday"); 9} 10 11fun main() { 12 val day = WeekDay.MONDAY 13 println(day.day) 14}
The output of the above code will be 'Monday'. Each Enum value comes with its 'day' value.
Notice how 'val day: String' holds different values for different Enum constants. This way, each day of the week gets its own string value.
Kotlin Enum with its collection of components, inbuilt properties, and methods empowers developers possessing the knowledge to implement it with a greater reach of capabilities.
Let’s discuss some advanced topics related to Kotlin Enum, such as Enum classes implementing interfaces, the role of anonymous classes, and the range of methods, properties, and unique functionalities of Kotlin Enum.
In Kotlin, enum constants can behave as anonymous classes, allowing for a more nuanced implementation of enum functionality. This is particularly evident when discussing the concept of abstract fun foo. Each enum constant has the potential to override this abstract function, demonstrating the flexibility and power of Kotlin's enum classes in supporting complex behaviors.
For example, by using override fun foo within an enum constant, developers can provide specific implementations for each constant, effectively allowing these constants to behave as unique instances of anonymous classes. This capability to override functions within enums showcases the versatility of Kotlin enums in accommodating sophisticated programming paradigms.
Enum classes in Kotlin are far from just a collection of Enum constants. They can also implement interfaces. However, they can't derive from a class since they implicitly inherit from the Enum class.
Here is an example where an enum class implements an interface:
1interface Printable { 2 fun print() 3} 4 5enum class Color(val rgb: Int) : Printable { 6 RED(0xFF0000) { 7 override fun print() { 8 println("Red Color") 9 } 10 }, 11 GREEN(0x00FF00) { 12 override fun print() { 13 println("Green Color") 14 } 15 }, 16 BLUE(0x0000FF) { 17 override fun print() { 18 println("Blue Color") 19 } 20 } 21} 22 23fun main() { 24 Color.RED.print() 25 Color.BLUE.print() 26 Color.GREEN.print() 27}
In addition to defining the Enum constants, anonymous class bodies are provided, which causes each object to have its own definition for the method 'print()'. So, when the 'print()' method is called on each Enum constant, it prints a different result - defined in its anonymous class. The Enum class allows different values to be attached to each enum constant, but also different behavior.
In more detail, this enum 'Color' is more than just some color constants. It also serves as a Kotlin string enum, and when its 'print()' function is invoked, it prints the string attached to the enumeration constant.
This Kotlin Enum example shows the vast capabilities that enums in Kotlin bring to the table. It attests to the vitality of enums in Kotlin in writing bulletproof, error-prone code.
To sum up, Kotlin enums are a powerful feature that enhances type safety in your code. They limit a variable to having one among a predefined set of values, making your code more robust and less prone to errors. Kotlin enums aren't just a mere collection of constants; they come with inbuilt properties and methods, and they can declare their own anonymous classes too.
With enums, you can represent a finite set of values more intuitively, such as the days of a week, colors in a rainbow, or the planets in the solar system. They support generic programming by allowing you to associate custom values or functions with your enum constants.
Enum classes can also implement interfaces. This means you can use enums as a fully-featured class. Therefore, the possibilities with enums in Kotlin are endless.
Check out the Kotlin documentation for more detailed information on defining enums, their values, properties and use-cases, and other features of enum classes.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.