CodeGym /Courses /Kotlin SELF /enum class: values, parameters, methods, and declaration ...

enum class: values, parameters, methods, and declaration rules

Kotlin SELF
Level 34, Lesson 0
Available

1. Why you need enum class

If you have ever written something like if (category == "food"), then you are already on the path to an ancient evil called “magic strings”. They are “magic” because any typo turns logic into a pumpkin: "Food", "FOOD", "food ", and "fod" look almost identical to a human, but for a program they are different values. In the end the program is not broken by the compiler — it is broken by real life.

enum class is a way to tell the compiler: “Here is the complete list of valid options. There cannot be any others.” And then Kotlin starts helping you: it checks types, suggests options in the IDE, and complains if you try to assign something “not from the list”.

Let’s imagine a small table to feel the difference:

Approach What we store What can go wrong
Strings
"FOOD", "food", "food"
typos, different letter case, different languages, extra spaces
enum class
Category.FOOD
practically only mistakes when parsing user input (and that is solvable)

And one more real-life example: expense categories. If you store a category as a string, one day you will end up with both "Transport" and "TRANSPORT", and the “by category” report will suddenly show two almost identical categories. That is not a bug — it is a “user input feature”, but you will be the one suffering.

Minimal enum

When people say “enum”, they often imagine something scary and corporate. In reality, the basic form is as simple as it gets: you list options separated by commas. Each option (also called an enum entry) is a ready-made value of the enum type.

Here is the most minimal example:

enum class Status { NEW, IN_PROGRESS, DONE }

fun main() {
    val s: Status = Status.DONE
    println(s) // DONE
}

Here Status.DONE is not a string, not a number, and not “just text”. It is a value of type Status. And Kotlin will now prevent you from accidentally assigning something else there:

enum class Status { NEW, IN_PROGRESS, DONE }

fun main() {
    val s: Status = Status.DONE
    // s = "DONE" // not allowed: String type does not match
}

Key idea: an enum is a “type with a fixed set of values”. That is exactly why enum replaces strings so well in places where “the options are known in advance”.

name and ordinal

When you print an enum via println(s), Kotlin usually prints the entry name (DONE). That is not an accident: every enum value has standard properties name and ordinal. name is the string name of the constant, and ordinal is its zero-based index. This is standard enum behavior in Kotlin.

Let’s see:

enum class Status { NEW, IN_PROGRESS, DONE }

fun main() {
    println(Status.NEW.name)       // NEW
    println(Status.NEW.ordinal)    // 0
    println(Status.DONE.ordinal)   // 2
}

name is usually useful for debugging and simple output. But ordinal sounds tempting (“oh, a free index!”) — and that is a trap.

Imagine you saved ordinal to a file as the “status code”, and then decided to reorder the entries:

enum class Status { NEW, DONE, IN_PROGRESS } // changed the order

That is it: now DONE has a different ordinal. That means old data will start being read incorrectly. Therefore, ordinal must not be considered a stable identifier if the order can change (and it almost always can — at least because you wanted it to look “nicer”).

If you need a stable identifier, make it explicit as an enum parameter.

All enum values: entries, values(), and valueOf

A practical question comes up almost immediately: “How do I show the user a list of all categories?” or “How do I iterate over all values?”. Enums have synthetic (that is, compiler-generated) ways to get “all values of the enumeration”.

Modern Kotlin provides the entries property, which returns a specialized list of all entries.

Example:

enum class Category { FOOD, TRANSPORT, BOOKS }

fun main() {
    for (c in Category.entries) {
        println(c.name)
    }
    // FOOD
    // TRANSPORT
    // BOOKS
}

Previously (and in many older examples on the internet) you will see values() — it returns an array. But nowadays entries is considered the better option: it does not allocate a new array on every call and it feels more “collection-like”. Kotlin officially notes that before entries appeared, values() was used.

Another useful thing is valueOf("NAME"), which returns an enum by its string name. But it has a personality: if you pass an unknown name, it throws IllegalArgumentException. In other words, valueOf is “strict parsing” — it works well when you are confident in the input.

Enum with parameters

Up to this point the enum looked like just a list of words. But in a real project you often need each entry to have its “own description”, “code”, “human-readable name”, “limit”, etc. And here comes the pleasant part: an enum can have constructor parameters — almost like a regular class.

Let’s make expense categories “human-friendly”: with an English display name and, for example, a stable code.

enum class Category(val code: Int, val title: String) {
    FOOD(10, "Food"),
    TRANSPORT(20, "Transport"),
    BOOKS(30, "Books")
}

fun main() {
    println(Category.FOOD.title)   // Food
    println(Category.FOOD.code)    // 10
}

Now instead of ordinal we have code, and it is stable because we set it ourselves. Reorder entries, add new ones — code will not change on its own. This is a great approach if you plan to persist the category somewhere external: to a file, a database, or over the network.

And title is exactly what you will show the user in the UI or in a report, so you do not print TRANSPORT in all caps (although if you like the “shouting accountant” style, why not).

Methods inside an enum

Data is great, but sometimes you want an enum entry to do something useful. That is normal: an enum is a class, and its entries are objects of that class. So an enum can have methods that use parameters (code, title, etc.).

Let’s make a method that formats a category for output:

enum class Category(val code: Int, val title: String) {
    FOOD(10, "Food"),
    TRANSPORT(20, "Transport"),
    BOOKS(30, "Books");

    fun label(): String = "$title (#$code)"
}

fun main() {
    println(Category.TRANSPORT.label()) // Transport (#20)
}

Notice the ; after the list of entries. It is not a decorative semicolon “for credibility”, but a syntactic rule: if an enum has a body (methods, properties), then a separator ; is required after the last enum entry.

Why? Because otherwise it is hard for the parser to understand where the list of constants ends and the class members begin. And Kotlin tries to make compilation errors understandable rather than “something went wrong in the depths of the universe”.

Commas and ; in enums

In practice, the most painful part of enums is not the idea and not the logic, but “why it does not compile, I just added a method”. Usually the answer is: “because you forgot the ;”.

You can remember the rule like this: as long as you are only listing entries, it is a “list” separated by commas. As soon as you want to add anything else (method/property), you put ;, and after that comes the “regular class body”.

Here is a correct template:

enum class Category(val title: String) {
    FOOD("Food"),
    TRANSPORT("Transport"),
    BOOKS("Books");

    fun upperTitle(): String = title.uppercase()
}

And one more small nuance from the same area: the comma between enum entries is mandatory (except after the last one). And ; is placed after the last entry if there are class members below.

If IntelliJ highlights it in red and says something like “Expecting member declaration” or “There must be a semicolon after the last enum entry” — you have almost certainly hit exactly this case.

2. Example: enum in console expense tracking

Now let’s do the most useful thing: apply enums not “in a vacuum”, but in our training console application. Imagine we already have a simple expense model (we created it earlier using data class) and somewhere in the program we keep a list of expenses. Previously the category could be a string, but we want type safety.

Introduce Category as an enum

Let’s start with the basics: list the categories. To make it convenient for the user, we will give each category a “human-readable name”.

enum class Category(val title: String) {
    FOOD("Food"),
    TRANSPORT("Transport"),
    BOOKS("Books")
}

Update the expense model

Now Expense stores category as Category, not String.

data class Expense(
    val amount: Int,
    val category: Category,
    val note: String
)

Safely parse the category from input

The user will type something like food or FOOD. But Category.valueOf(...) requires an exact name and can also throw an exception.

So for “user input” it is better to implement lenient parsing: normalize the string and search among entries.

Here is a neat function:

fun parseCategoryOrNull(raw: String): Category? {
    val key = raw.trim().uppercase()
    return Category.entries.firstOrNull { it.name == key }
}

Here entries gives us a list of all enum entries. If the user typed something unknown, we get null, and then we handle it in input logic (without crashing).

For clarity, here is a mini-diagram of this process:

flowchart TD
    A["User entered a string"] --> B["trim()"]
    B --> C["uppercase()"]
    C --> D["search Category.entries by name"]
    D -->|found| E["return Category"]
    D -->|not found| F["return null"]

Add an expense: read → parse → create an object

Let’s put together a small function for adding an expense. Let the format be simple: amount, category, note (the note is the rest of the line).

fun addExpense(rawAmount: String, rawCategory: String, note: String): Expense? {
    val amount = rawAmount.trim().toIntOrNull() ?: return null
    val category = parseCategoryOrNull(rawCategory) ?: return null
    return Expense(amount = amount, category = category, note = note.trim())
}

And test it with a mini-example:

fun main() {
    val e = addExpense("120", "food", "lunch") ?: return
    println(e) // Expense(amount=120, category=FOOD, note=lunch)
}

For now the output for category will be FOOD, because that is name. But for the user we will show title:

fun main() {
    val e = addExpense("120", "food", "lunch") ?: return
    println("${e.amount} ₣  — ${e.category.title} (${e.note})")
    // 120 ₣  — Food (lunch)
}

User hint: which categories exist

Since we have an enum, we can easily print the list of categories:

fun printCategories() {
    val text = Category.entries.joinToString { it.name.lowercase() }
    println("Categories: $text")
    // Categories: food, transport, books
}

entries is again used here as the “source of truth” for all options.

This approach is good because if you add the category HEALTH("Health"), the hint will update automatically (and you will not have to remember where you manually printed a list of strings).

3. Common mistakes when working with enum class

Mistake №1: keep storing options as strings “because it is faster”.
Sometimes it seems like String is simpler: read, compare, done. But as soon as you have reporting, filtering, stats, and at least one user who types food with a trailing space, you will start wasting time on “string normalization” in a dozen places. Enums move the problem into one place: input parsing. And inside the program the values become strict and consistent.

Mistake №2: use ordinal as a stable identifier.
ordinal depends on declaration order. Today FOOD has ordinal = 0, tomorrow you reordered entries — and everything breaks silently, without warnings. ordinal is fine for very local things (for example, “show the position in a list right now”), but not for storage and not for protocols. If you need a stable code, add your own field, for example code.

Mistake №3: forget the ; before enum methods and properties.
This is a classic: you declared entries, then added a method — and the compiler suddenly starts complaining out of nowhere. The reason is simple: if an enum has class members, the list of entries must be separated by ;. This is a Kotlin enum rule, and it is truly mandatory.

Mistake №4: parse user input via valueOf() without protection.
valueOf("FOOD") is convenient, but if the string does not match, it throws IllegalArgumentException. For “external data” (user input), you often need safe parsing: via entries.firstOrNull { ... } to get null and show a clear message instead of crashing with an exception.

Mistake №5: mix up the “human-readable name” and the enum entry’s name.
name is the technical name of the constant (FOOD). It is great for code and debugging, but it often does not look very friendly for users. If you want nice output, add a field like title: String and display it. That way you do not tie the UI to technical names, and you can change the display text without rewriting the logic.

1
Task
Kotlin SELF, level 34, lesson 0
Locked
Progress Board
Progress Board
1
Task
Kotlin SELF, level 34, lesson 0
Locked
Bot Mood
Bot Mood
1
Task
Kotlin SELF, level 34, lesson 0
Locked
Drink vending machine
Drink vending machine
1
Task
Kotlin SELF, level 34, lesson 0
Locked
Startup mode
Startup mode
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION