kotlin enum
Kotlin enum is a special data type that allows you to define a set of constant values. Here are the steps to create and use enums in Kotlin:
- Start by declaring an enum class using the "enum" keyword followed by the name of the enum class. For example:
enum class Color { RED, GREEN, BLUE }
Inside the curly braces, list the constant values that the enum class can have. In the example above, the enum class "Color" has three constant values: RED, GREEN, and BLUE.
To use the enum class, you can simply refer to its constant values by their names. For example:
val myColor = Color.RED
- You can also use enums in when expressions to perform different actions based on the enum's constant value. For example:
when (myColor) { Color.RED -> println("The color is red") Color.GREEN -> println("The color is green") Color.BLUE -> println("The color is blue") }
- Enums can also have properties and methods. You can define properties for each enum constant and access them using dot notation. For example:
enum class Direction(val degrees: Int) { NORTH(0), EAST(90), SOUTH(180), WEST(270) }
val myDirection = Direction.NORTH println(myDirection.degrees) // Output: 0
- You can also define methods in enum classes. These methods can be called on each enum constant. For example:
enum class Direction { NORTH { override fun printDirection() { println("Facing north") } }, EAST { override fun printDirection() { println("Facing east") } }, SOUTH { override fun printDirection() { println("Facing south") } }, WEST { override fun printDirection() { println("Facing west") } };
abstract fun printDirection() }
val myDirection = Direction.NORTH myDirection.printDirection() // Output: Facing north
That's it! These are the steps to create and use enums in Kotlin. Enums are a powerful tool for defining a fixed set of values and can be used in various scenarios to enhance your code's readability and maintainability.