Enums help group related values together. Adding properties and methods makes each value more useful and descriptive.
0
0
Enum with properties and methods in Kotlin
Introduction
When you want to represent a fixed set of related constants with extra details.
When each option needs its own behavior or data.
When you want to organize code clearly instead of using many separate variables.
When you want to avoid mistakes by limiting choices to predefined options.
When you want to add functions that work differently for each enum value.
Syntax
Kotlin
enum class EnumName(val propertyName: PropertyType) { VALUE1(propertyValue1) { override fun methodName() { // code for VALUE1 } }, VALUE2(propertyValue2) { override fun methodName() { // code for VALUE2 } }; abstract fun methodName() }
Each enum value can have its own property values and method implementations.
The abstract method must be implemented by all enum values.
Examples
This enum represents directions with degrees and a description method.
Kotlin
enum class Direction(val degrees: Int) { NORTH(0) { override fun description() = "Upwards" }, EAST(90) { override fun description() = "Rightwards" }, SOUTH(180) { override fun description() = "Downwards" }, WEST(270) { override fun description() = "Leftwards" }; abstract fun description(): String }
This enum models traffic lights with color and an action method.
Kotlin
enum class Light(val color: String) { RED("Red") { override fun action() = "Stop" }, YELLOW("Yellow") { override fun action() = "Get Ready" }, GREEN("Green") { override fun action() = "Go" }; abstract fun action(): String }
Sample Program
This program defines planets with mass and radius. Each planet has its own surface gravity method. The main function prints details for each planet.
Kotlin
enum class Planet(val mass: Double, val radius: Double) { EARTH(5.972e24, 6371.0) { override fun surfaceGravity() = 9.807 }, MARS(0.64171e24, 3389.5) { override fun surfaceGravity() = 3.721 }; abstract fun surfaceGravity(): Double } fun main() { for (planet in Planet.values()) { println("${planet.name} has mass ${planet.mass} kg and surface gravity ${planet.surfaceGravity()} m/s²") } }
OutputSuccess
Important Notes
Remember to put a semicolon (;) before defining methods if enum values have bodies.
Properties can be used like normal class properties.
Methods can be abstract or concrete inside the enum class.
Summary
Enums group fixed related values with extra data and behavior.
Each enum value can have its own properties and methods.
This helps write clear and organized code for fixed sets of options.