Skip to main content
ubuntuask.com

Back to all posts

How to Create And Use Enums In Kotlin?

Published on
6 min read
How to Create And Use Enums In Kotlin? image

Best Kotlin Programming Books to Buy in October 2025

1 Head First Kotlin: A Brain-Friendly Guide

Head First Kotlin: A Brain-Friendly Guide

BUY & SAVE
$50.36 $79.99
Save 37%
Head First Kotlin: A Brain-Friendly Guide
2 Android Programming with Kotlin for Beginners: Build Android apps starting from zero programming experience with the new Kotlin programming language

Android Programming with Kotlin for Beginners: Build Android apps starting from zero programming experience with the new Kotlin programming language

BUY & SAVE
$33.00 $38.99
Save 15%
Android Programming with Kotlin for Beginners: Build Android apps starting from zero programming experience with the new Kotlin programming language
3 Kotlin in Action, Second Edition

Kotlin in Action, Second Edition

BUY & SAVE
$45.98 $59.99
Save 23%
Kotlin in Action, Second Edition
4 Head First Android Development: A Learner's Guide to Building Android Apps with Kotlin

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

BUY & SAVE
$59.30 $89.99
Save 34%
Head First Android Development: A Learner's Guide to Building Android Apps with Kotlin
5 Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines

Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines

BUY & SAVE
$48.00 $65.99
Save 27%
Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines
6 Kotlin In-Depth: A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile (English Edition)

Kotlin In-Depth: A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile (English Edition)

BUY & SAVE
$29.95 $32.95
Save 9%
Kotlin In-Depth: A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile (English Edition)
7 Kotlin from Scratch: A Project-Based Introduction for the Intrepid Programmer

Kotlin from Scratch: A Project-Based Introduction for the Intrepid Programmer

BUY & SAVE
$36.20 $59.99
Save 40%
Kotlin from Scratch: A Project-Based Introduction for the Intrepid Programmer
8 Kotlin: An Illustrated Guide

Kotlin: An Illustrated Guide

BUY & SAVE
$49.62
Kotlin: An Illustrated Guide
+
ONE MORE?

In Kotlin, enums are used to represent a fixed number of constant values. They provide a way to define a collection of related constants and are commonly used to define a set of options or states.

To create an enum in Kotlin, you start with the enum keyword followed by the name of the enum. Inside the body of the enum, you define each constant value as a separate entry.

enum class Direction { NORTH, SOUTH, EAST, WEST }

Here, an enum called Direction is created with four constant values: NORTH, SOUTH, EAST, and WEST. Each enum value is defined using a comma-separated list, and conventionally written in uppercase.

Enums can also have properties and functions associated with them. For example:

enum class Planet(val mass: Double, val radius: Double) { EARTH(5.972e24, 6_371.0), MARS(6.39e23, 3_389.5), MOON(7.342e22, 1_737.1);

fun calculateSurfaceGravity(): Double {
    val G = 6.67300e-11
    return G \* mass / (radius \* radius)
}

}

In this example, the enum Planet has additional properties mass and radius associated with each constant value. It also has a function calculateSurfaceGravity() which can be invoked on each enum instance.

To use an enum, you can either refer to one of its constants by name or obtain an array of all the enum values. For example:

val direction: Direction = Direction.NORTH println(direction) // Output: NORTH

val allDirections: Array = Direction.values() println(allDirections.joinToString()) // Output: NORTH, SOUTH, EAST, WEST

In Kotlin, enums are considered as first-class citizens and can be used widely as a more powerful replacement for Java enums. They can have their own properties, methods, and implement interfaces, making them quite flexible.

What happens when you convert an enum constant to a string in Kotlin?

When you convert an enum constant to a string in Kotlin, the name of the enum constant is returned as a string.

Let's say you have an enum class called Color, and it has constants RED, GREEN, and BLUE. When you convert the enum constant RED to a string, it will return the string "RED". Similarly, GREEN and BLUE will return "GREEN" and "BLUE" respectively.

Here's an example:

enum class Color { RED, GREEN, BLUE }

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

In the example above, the toString() method is implicitly called when you assign the enum constant Color.RED to a string variable colorString. This converts the enum constant to a string representation with the name "RED".

What is the default value of an enum constant in Kotlin?

In Kotlin, the default value of an enum constant is the name of the constant itself.

How to use enum constants as properties in Kotlin classes?

To use enum constants as properties in Kotlin classes, you can follow these steps:

Step 1: Declare an enum class:

enum class Color { RED, GREEN, BLUE }

Step 2: Create a class and define a property of the enum type:

class Car(val color: Color) { // Other properties and methods }

Step 3: Create an instance of the class and pass an enum constant as an argument:

val car = Car(Color.GREEN)

Now, you can access the enum constant property of the class instance just like any other property:

println("The color of the car is ${car.color}")

This will output:

The color of the car is GREEN

You can also use the enum constant in when statements or as parameters in functions. For example:

fun printCarInfo(car: Car) { when (car.color) { Color.RED -> println("The car is red") Color.GREEN -> println("The car is green") Color.BLUE -> println("The car is blue") } }

Now, if you call the printCarInfo function with a Car instance, it will print the corresponding color information.

How to add methods to enum classes in Kotlin?

In Kotlin, you can add methods to enum classes by using the enum keyword combined with a class declaration.

Here's an example:

enum class Color { RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET;

fun printColorName() {
    println(name.toLowerCase().capitalize()) // Example method implementation
}

}

In the example above, we have defined an enum class named Color containing a list of colors. After the enum values (RED, ORANGE, etc.), you can define additional methods like printColorName().

To use the added method, you can call it on any instance of the enum class:

val color = Color.RED color.printColorName() // Output: Red

Note that enum classes in Kotlin are powerful and can have properties, custom constructors, and more, similar to regular classes.

What is the significance of the valueOf() function in Kotlin enums?

The valueOf() function in Kotlin enums is used to obtain an enum constant from its string representation. It is a predefined function that is automatically added to all enum classes in Kotlin.

The significance of the valueOf() function is that it provides a convenient way to convert a string into an enum constant, enabling developers to parse or deserialize enum values from external sources or user inputs.

For example, consider an enum called Color with constant values RED, GREEN, and BLUE. By using the valueOf() function, you can easily obtain the enum constant based on a given string, like Color.valueOf("RED").

However, it's important to note that the valueOf() function is case-sensitive and will throw an IllegalArgumentException if the string does not match any of the enum constant names. Thus, it's recommended to handle such exceptions when using the valueOf() function.

How to use enum constructors with parameters in Kotlin?

In Kotlin, you can use enum constructors with parameters by adding the parameters directly in the enum declaration. Here's an example:

enum class Color(val rgb: Int) { RED(0xFF0000), GREEN(0x00FF00), BLUE(0x0000FF) }

In this example, the Color enum has a parameter rgb of type Int. Each enum constant (RED, GREEN, BLUE) is created with a specific rgb value.

You can access the parameter value for each enum constant using the dot notation, like Color.RED.rgb.

Here's how you can use enum constructors with parameters:

fun main() { val redColor = Color.RED println("RGB value of Red color: ${redColor.rgb}") }

Output:

RGB value of Red color: 16711680

In this example, we create an instance redColor of the Color enum and access its rgb value using the dot notation.

Note that enum constants can have additional properties, methods, and implementations just like regular classes.