How to Define And Use Enums In Kotlin?

9 minutes read

In Kotlin, enums are used to represent a fixed set of constant values. They are similar to enums in other programming languages like Java. To define an enum in Kotlin, use the "enum class" keyword followed by the name of the enum.


Here's an example of defining an enum for days of the week:

1
2
3
4
5
6
7
8
9
enum class DayOfWeek {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}


In this example, we defined an enum called "DayOfWeek" with seven possible values: MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY.


To use an enum value, simply reference it by its name, like this:

1
val day = DayOfWeek.MONDAY


Enums can have properties and functions like normal classes. Here's an example of adding a property to our "DayOfWeek" enum:

1
2
3
4
5
6
7
8
9
enum class DayOfWeek(val isWeekend: Boolean) {
    MONDAY(false),
    TUESDAY(false),
    WEDNESDAY(false),
    THURSDAY(false),
    FRIDAY(false),
    SATURDAY(true),
    SUNDAY(true)
}


In this modified enum, we added a property called "isWeekend" which tells whether a particular day is a weekend or not.


To access the properties or call functions associated with an enum value, use the dot notation:

1
2
val day = DayOfWeek.SATURDAY
println(day.isWeekend) // Output: true


Enums can also be used in when expressions to perform pattern matching. Here's an example:

1
2
3
4
5
6
fun getDayType(day: DayOfWeek): String {
    return when (day) {
        DayOfWeek.SATURDAY, DayOfWeek.SUNDAY -> "Weekend"
        else -> "Weekday"
    }
}


In this example, the function "getDayType" takes a "DayOfWeek" enum value as an argument and returns a string indicating whether it's a weekend or a weekday.


Enums in Kotlin provide a convenient and type-safe way to define and work with a fixed set of values, making your code more readable and less error-prone.

Best Kotlin Books to Read in 2024

1
Atomic Kotlin

Rating is 5 out of 5

Atomic Kotlin

2
Kotlin in Action

Rating is 4.9 out of 5

Kotlin in Action

3
Java to Kotlin: A Refactoring Guidebook

Rating is 4.8 out of 5

Java to Kotlin: A Refactoring Guidebook

4
Programming Kotlin: Create Elegant, Expressive, and Performant JVM and Android Applications

Rating is 4.7 out of 5

Programming Kotlin: Create Elegant, Expressive, and Performant JVM and Android Applications

5
Modern Android 13 Development Cookbook: Over 70 recipes to solve Android development issues and create better apps with Kotlin and Jetpack Compose

Rating is 4.6 out of 5

Modern Android 13 Development Cookbook: Over 70 recipes to solve Android development issues and create better apps with Kotlin and Jetpack Compose

6
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.5 out of 5

Kotlin Cookbook: A Problem-Focused Approach

7
Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines

Rating is 4.4 out of 5

Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines

8
Kotlin and Android Development featuring Jetpack: Build Better, Safer Android Apps

Rating is 4.3 out of 5

Kotlin and Android Development featuring Jetpack: Build Better, Safer Android Apps


How to use enums in Kotlin?

To use enums in Kotlin, you can follow these steps:

  1. Define an enum class: Use the enum keyword followed by the class name and the list of enum constants enclosed in curly braces.
1
2
3
enum class Direction {
    NORTH, SOUTH, EAST, WEST
}


  1. Access enum constants: You can access enum constants by their name using the dot notation.
1
val direction = Direction.NORTH


  1. Use enum constants in conditional statements: You can use enum constants in conditional statements like when expressions.
1
2
3
4
5
6
when (direction) {
    Direction.NORTH -> println("The direction is north.")
    Direction.SOUTH -> println("The direction is south.")
    Direction.EAST -> println("The direction is east.")
    Direction.WEST -> println("The direction is west.")
}


  1. Use enum properties and methods: Enums can have properties and methods like regular classes. You can define properties and methods inside the enum class body.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
enum class Direction {
    NORTH, SOUTH, EAST, WEST;

    val opposite: Direction
        get() = when (this) {
            NORTH -> SOUTH
            SOUTH -> NORTH
            EAST -> WEST
            WEST -> EAST
        }

    fun isHorizontal(): Boolean {
        return this == EAST || this == WEST
    }
}

val direction = Direction.NORTH
val oppositeDirection = direction.opposite // Returns Direction.SOUTH

println(direction.isHorizontal()) // Prints false


In this example, the opposite property returns the opposite direction, and the isHorizontal() method checks if the direction is horizontal.


These are the basic steps to use enums in Kotlin. Enums provide a way to represent a fixed set of values and make the code more readable and maintainable.


What are sealed classes in relation to enums?

Sealed classes are classes that cannot be inherited or extended by other classes. They are used to restrict the inheritance hierarchy and ensure no other classes can derive from it.


In relation to enums, a sealed class can be used instead of an enum when a finite set of values is needed. Enums in some programming languages provide a fixed set of predefined values, but they cannot be extended or used as a base class. On the other hand, a sealed class can define a set of predefined values and allow for further extension, providing more flexibility in comparison to enums.


By using a sealed class instead of an enum, you can create a hierarchy of classes that represents related values, and each subclass can have its own properties, methods, and behavior. This allows more complex operations based on the specific values represented by these classes, rather than just relying on simple constants provided by enums.


How to convert an enum to a string in Kotlin?

In Kotlin, you can convert an enum to a string by using the name property of the enum value. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
enum class Color {
    RED,
    GREEN,
    BLUE
}

fun main() {
    val color = Color.RED
    val colorString = color.name
    println(colorString) // Output: "RED"
}


In this example, we have an enum Color with three values: RED, GREEN, and BLUE. We can convert a specific color, such as Color.RED, to a string using the name property. The name property returns the name of the enum value as a string.


Note that the name property returns the name of the enum value exactly as it is defined in the enum, so it is case-sensitive.


How to check if a value exists in an enum in Kotlin?

In Kotlin, you can check if a value exists in an enum by using the enumValues<T>() function and the contains() method. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
enum class Color {
    RED, GREEN, BLUE
}

fun main() {
    val color = Color.RED

    if (enumValues<Color>().contains(color)) {
        println("$color exists in the Color enum.")
    } else {
        println("$color does not exist in the Color enum.")
    }
}


In this example, the enumValues<Color>() function returns an array of all the enum values. The contains() method is then used to check if the color variable exists in the enum.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

To install the Kotlin compiler, you can follow these steps:Firstly, ensure that you have Java Development Kit (JDK) installed on your system. Kotlin requires JDK version 6 or higher to run. Visit the official Kotlin website at kotlinlang.org and navigate to th...
Kotlin is a programming language developed by JetBrains, designed to be a more concise and expressive alternative to Java for Android development. Here is a general overview of how to use Kotlin for Android development:Installation: Start by installing the Kot...
Nullability is a key feature in Kotlin that helps prevent null pointer exceptions. In Kotlin, nullability is explicitly expressed in types, which allows you to handle nullable and non-nullable variables in a clear and concise manner.By default, variables in Ko...