0
0
Kotlinprogramming~5 mins

Enum class declaration in Kotlin

Choose your learning style9 modes available
Introduction

An enum class helps you group related constant values under one name. It makes your code easier to read and use.

When you want to list fixed options like days of the week.
When you need to represent states like ON or OFF.
When you want to avoid using many separate constants.
When you want to use meaningful names instead of numbers or strings.
When you want to use special behavior for each constant.
Syntax
Kotlin
enum class EnumName {
    CONSTANT1,
    CONSTANT2,
    CONSTANT3
}

Each constant is written in uppercase by convention.

You can add properties and functions inside the enum class if needed.

Examples
This enum lists four directions.
Kotlin
enum class Direction {
    NORTH, SOUTH, EAST, WEST
}
This enum represents traffic light colors.
Kotlin
enum class Light {
    RED, YELLOW, GREEN
}
This enum has a property to mark weekend days.
Kotlin
enum class Day(val isWeekend: Boolean) {
    MONDAY(false), TUESDAY(false), WEDNESDAY(false), THURSDAY(false), FRIDAY(false), SATURDAY(true), SUNDAY(true)
}
Sample Program

This program declares an enum for seasons and prints the current one.

Kotlin
enum class Season {
    SPRING, SUMMER, FALL, WINTER
}

fun main() {
    val current = Season.SUMMER
    println("Current season is $current")
}
OutputSuccess
Important Notes

Enum constants are objects and can have their own properties and methods.

You can use enums in when expressions for clear and safe branching.

Summary

Enum classes group fixed sets of constants under one type.

They improve code clarity and safety by replacing magic numbers or strings.

You can add properties and functions to enum constants for extra behavior.