How to Create And Use Enums In Kotlin?

12 minutes read

In Kotlin, enums are a type that allows you to define a collection of constant values. They are used to represent a fixed number of possible values for a property or a variable. Enum classes make your code more readable and help to avoid errors by restricting the allowed values.


To create an enum in Kotlin, you use the enum class keyword followed by the name of your enum. Within the enum class, you define the values or constants by listing them out separated by commas.


Here is an example of creating an enum class called Color with three constant values - RED, GREEN, and BLUE:

1
2
3
4
5
enum class Color {
    RED,
    GREEN,
    BLUE
}


To use an enum, you can simply refer to its name followed by the value you want to access. For example, to use the GREEN value from the Color enum, you can write Color.GREEN.


Enums also come with useful built-in functions. One of them is values(), which returns an array of all the values defined in the enum. Additionally, you can access the ordinal value of an enum constant using the ordinal property.

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

fun main() {
    val colors = Color.values() // Returns an array of enum values

    for (color in colors) {
        println("${color.name} is at index ${color.ordinal}")
    }
}


In the above example, the values() function is used to retrieve an array of all the enum values. Then, a loop is used to iterate over each value and print its name and ordinal value.


Enums in Kotlin can also have properties, methods, and implement interfaces, making them more versatile than traditional enum types in some other languages.

Best Kotlin Books to Read in 2024

1
Atomic Kotlin

Rating is 5 out of 5

Atomic Kotlin

2
Head First Android Development: A Learner's Guide to Building Android Apps with Kotlin

Rating is 4.9 out of 5

Head First Android Development: A Learner's Guide to Building Android Apps with Kotlin

3
Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

Rating is 4.8 out of 5

Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

4
Kotlin in Action

Rating is 4.7 out of 5

Kotlin in Action

5
Kotlin Design Patterns and Best Practices: Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin, 2nd Edition

Rating is 4.6 out of 5

Kotlin Design Patterns and Best Practices: Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin, 2nd Edition

6
Head First Kotlin: A Brain-Friendly Guide

Rating is 4.5 out of 5

Head First Kotlin: A Brain-Friendly Guide

7
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.4 out of 5

Kotlin Cookbook: A Problem-Focused Approach

8
How to Build Android Apps with Kotlin: A practical guide to developing, testing, and publishing your first Android apps, 2nd Edition

Rating is 4.3 out of 5

How to Build Android Apps with Kotlin: A practical guide to developing, testing, and publishing your first Android apps, 2nd Edition

9
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.2 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

10
Java to Kotlin: A Refactoring Guidebook

Rating is 4.1 out of 5

Java to Kotlin: A Refactoring Guidebook


What is the best practice for defining enum constants in Kotlin?

In Kotlin, the best practice for defining enum constants is as follows:

  1. Define the enum class using the enum keyword.
  2. List all the enum constants in all uppercase letters, separated by commas.
  3. Optionally, you can add additional properties, methods, or even implement interfaces to the enum class.


Here's an example of how to define enum constants in Kotlin:

1
2
3
enum class Color {
    RED, GREEN, BLUE
}


You can access the enum constants using the enum class name followed by a dot notation. For example, to access the RED constant, you would use Color.RED.


You can also define additional properties or methods to each enum constant. Here's an example:

1
2
3
4
5
6
7
8
9
enum class Color(val rgb: Int) {
    RED(0xFF0000),
    GREEN(0x00FF00),
    BLUE(0x0000FF);

    fun getHexCode(): String {
        return "#${Integer.toHexString(rgb)}"
    }
}


In this example, each color constant has an associated RGB value, and there's a getHexCode() method to retrieve the color's hexadecimal code.


By following these practices, you can define enum constants in a clear and concise manner in Kotlin.


How to compare enum constants in Kotlin?

In Kotlin, enum constants can be compared using the == operator.


Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
enum class Fruit {
    APPLE,
    BANANA,
    ORANGE
}

fun main() {
    val fruit1 = Fruit.APPLE
    val fruit2 = Fruit.BANANA

    if (fruit1 == fruit2) {
        println("Both fruits are the same.")
    } else {
        println("Both fruits are different.")
    }
}


Output:

1
Both fruits are different.


In this example, we have two enum constants APPLE and BANANA. We compare them using the == operator in the if condition. Since they are different, the output is "Both fruits are different."


What are the advantages of using enums in Kotlin?

There are several advantages of using enums in Kotlin:

  1. Type-Safe: Enums provide type-safety, meaning only the predefined constants of the enum can be used. This helps in catching errors at compile-time, making the code more robust.
  2. Readability: Enum constants can be given descriptive names, making the code more readable and self-explanatory. It enhances the clarity of the code by conveying the meaning of the constant.
  3. Singleton Pattern: Each constant in an enum is a singleton instance, meaning only one instance of each constant is created. This helps in creating a limited number of instances and avoids unnecessary object creation.
  4. Method and Property implementation: Enums can have methods and properties just like any other class in Kotlin. This allows you to define specific behavior or attributes for each constant, making the code more organized and modular.
  5. Iteration and Comparison: Enums provide built-in features to iterate over all the constants or to compare them. This can be useful when dealing with a fixed set of options or when performing operations based on different enum values.
  6. Switching with When Expressions: Kotlin's when expression works really well with enums. It allows you to handle different cases based on enum constants easily, making the code more concise and readable.


Overall, enums in Kotlin provide a powerful tool for representing a set of related constants in a type-safe and expressive manner, improving code quality and maintainability.


What is the role of the semicolon after the last enum constant declaration in Kotlin?

In Kotlin, an semicolon after the last enum constant declaration serves as a separator between the enum constants and the additional properties or functions defined within the enum class.


Here's an example to demonstrate this:


enum class Day { MONDAY, TUESDAY, WEDNESDAY;

1
2
3
fun isWeekend(): Boolean {
    return this == SATURDAY || this == SUNDAY
}


}


In the above code snippet, the semicolon after the enum constant declaration 'WEDNESDAY' separates it from the following function 'isWeekend()'.


How to override equals() method for comparing enum constants in Kotlin?

To override the equals() method for comparing enum constants in Kotlin, follow these steps:

  1. Create an enum class.
  2. Implement the equals() method inside the enum class.
  3. Use the == operator to compare the enum constants in the equals() method.
  4. Handle the case when both enum constants are null.
  5. Use the name property to compare the names of the enum constants.


Here is an example of how to override the equals() method for comparing enum constants in Kotlin:

1
2
3
4
5
6
7
8
9
enum class Direction {
    NORTH, SOUTH, EAST, WEST;

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other !is Direction) return false
        return this.name == other.name
    }
}


Now you can use the equals() method to compare enum constants:

1
2
3
4
5
6
val direction1 = Direction.NORTH
val direction2 = Direction.SOUTH
val direction3 = Direction.NORTH

println(direction1.equals(direction2))  // Output: false
println(direction1.equals(direction3))  // Output: true


In the above example, direction1.equals(direction2) returns false because the names of the enum constants NORTH and SOUTH are not equal. However, direction1.equals(direction3) returns true because the names of the enum constants NORTH and NORTH are equal.

Facebook Twitter LinkedIn Whatsapp Pocket

Related Posts:

In Kotlin, extension functions allow you to add new functionality to existing classes without modifying their source code. They provide a way to extend the behavior of classes from external libraries or even built-in classes. Here is how you can define and use...
In Kotlin, higher-order functions are functions that can take other functions as parameters or return functions as their values. It is an essential feature of functional programming and allows you to write more concise and reusable code.To work with higher-ord...
In Kotlin, classes are the building blocks of object-oriented programming. They encapsulate data and behavior, allowing you to define custom types. Here's a brief explanation of how to create and use classes in Kotlin:To create a class, use the "class&...