Kotlin enum

Introduction

In Kotlin, the enum class represents a type that consists of a fixed set of constants. Enums are commonly used to represent a collection of related values that are known at compile time, such as days of the week, directions, states, etc. They provide a type-safe way to define and use constants.

Table of Contents

  1. What is an enum Class?
  2. Creating enum Classes
  3. Accessing enum Constants
  4. Enum Properties and Methods
  5. Enum Functions
  6. Examples of enum
  7. Real-World Use Case
  8. Conclusion

1. What is an enum Class?

An enum class in Kotlin is a special type that represents a group of constants. Each constant is an instance of the enum class, and enums can have properties, methods, and implement interfaces.

Syntax

enum class Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

2. Creating enum Classes

To create an enum class, use the enum keyword followed by the class name and a list of constants.

Example

enum class Color {
    RED, GREEN, BLUE
}

3. Accessing enum Constants

You can access enum constants using the dot notation.

Example

fun main() {
    val favoriteColor = Color.BLUE
    println("Favorite color is $favoriteColor")
}

4. Enum Properties and Methods

Enums can have properties and methods. You can define properties and methods just like in regular classes.

Example

enum class Day(val isWeekend: Boolean) {
    SUNDAY(true),
    MONDAY(false),
    TUESDAY(false),
    WEDNESDAY(false),
    THURSDAY(false),
    FRIDAY(false),
    SATURDAY(true);

    fun printDayType() {
        if (isWeekend) {
            println("$this is a weekend")
        } else {
            println("$this is a weekday")
        }
    }
}

fun main() {
    Day.SATURDAY.printDayType()
    Day.MONDAY.printDayType()
}

Output:

SATURDAY is a weekend
MONDAY is a weekday

5. Enum Functions

Kotlin provides several useful functions for working with enums:

  • values(): Returns an array of all enum constants.
  • valueOf(name: String): Returns the enum constant with the specified name.

Example

fun main() {
    // Using values()
    val days = Day.values()
    for (day in days) {
        println(day)
    }

    // Using valueOf()
    val day = Day.valueOf("MONDAY")
    println("Day: $day")
}

Output:

SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
Day: MONDAY

6. Examples of enum

Example 1: Enum with Properties

This example demonstrates defining an enum with properties and methods.

enum class Direction(val degrees: Int) {
    NORTH(0),
    EAST(90),
    SOUTH(180),
    WEST(270);

    fun printDirection() {
        println("Direction $this is $degrees degrees from NORTH")
    }
}

fun main() {
    Direction.NORTH.printDirection()
    Direction.EAST.printDirection()
}

Output:

Direction NORTH is 0 degrees from NORTH
Direction EAST is 90 degrees from NORTH

Explanation:
This example defines an enum Direction with a property degrees and a method printDirection.

Example 2: Enum Implementing Interface

This example demonstrates an enum implementing an interface.

interface Printable {
    fun print()
}

enum class Status : Printable {
    PENDING {
        override fun print() {
            println("Pending status")
        }
    },
    COMPLETED {
        override fun print() {
            println("Completed status")
        }
    },
    FAILED {
        override fun print() {
            println("Failed status")
        }
    }
}

fun main() {
    Status.PENDING.print()
    Status.COMPLETED.print()
    Status.FAILED.print()
}

Output:

Pending status
Completed status
Failed status

Explanation:
This example defines an enum Status that implements the Printable interface.

Example 3: Enum with Custom Methods

This example demonstrates an enum with custom methods.

enum class Planet(val mass: Double, val radius: Double) {
    MERCURY(3.303e+23, 2.4397e6),
    VENUS(4.869e+24, 6.0518e6),
    EARTH(5.976e+24, 6.37814e6),
    MARS(6.421e+23, 3.3972e6);

    // Universal gravitational constant  (m3 kg-1 s-2)
    val G = 6.67300e-11

    fun surfaceGravity(): Double {
        return G * mass / (radius * radius)
    }

    fun surfaceWeight(otherMass: Double): Double {
        return otherMass * surfaceGravity()
    }
}

fun main() {
    val earthWeight = 70.0
    val mass = earthWeight / Planet.EARTH.surfaceGravity()

    for (p in Planet.values()) {
        println("Your weight on ${p.name} is ${p.surfaceWeight(mass)}")
    }
}

Output:

Your weight on MERCURY is 26.46076506257041
Your weight on VENUS is 63.72066045970312
Your weight on EARTH is 70.0
Your weight on MARS is 26.46720159485788

Explanation:
This example defines an enum Planet with properties mass and radius, and methods to calculate surface gravity and surface weight.

7. Real-World Use Case: User Roles in an Application

Enums can be used to define user roles in an application.

Example: Defining User Roles

enum class UserRole(val permissions: List<String>) {
    ADMIN(listOf("READ", "WRITE", "DELETE")),
    USER(listOf("READ", "WRITE")),
    GUEST(listOf("READ"));

    fun printPermissions() {
        println("$this has permissions: ${permissions.joinToString()}")
    }
}

fun main() {
    UserRole.ADMIN.printPermissions()
    UserRole.USER.printPermissions()
    UserRole.GUEST.printPermissions()
}

Output:

ADMIN has permissions: READ, WRITE, DELETE
USER has permissions: READ, WRITE
GUEST has permissions: READ

Explanation:
This example defines an enum UserRole with a property permissions and a method printPermissions to display the permissions for each role.

Conclusion

The enum class in Kotlin provides a way to define a fixed set of constants and associate properties and methods with them. Enums are useful for representing a group of related values and can simplify the code by providing a type-safe way to work with constants. Understanding how to use enums and their features is essential for effective Kotlin programming, especially when dealing with predefined sets of values.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare