Kotlin

Enums with Properties and Methods

admin by @admin ADMIN
1h ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Kotlin enums can carry constructor properties and define methods — including abstract methods overridden per constant. Way more expressive than Java enums.
Kotlin
Raw
enum class Status(val label: String, val isFinal: Boolean) {
    PENDING("Awaiting review",  false),
    ACTIVE("In progress",        false),
    DONE("Completed",            true),
    CANCELLED("Cancelled",       true);

    fun canTransitionTo(target: Status): Boolean =
        !this.isFinal && this != target
}

enum class Operation {
    ADD      { override fun apply(a: Int, b: Int) = a + b },
    SUBTRACT { override fun apply(a: Int, b: Int) = a - b },
    MULTIPLY { override fun apply(a: Int, b: Int) = a * b },
    DIVIDE   { override fun apply(a: Int, b: Int) = a / b };

    abstract fun apply(a: Int, b: Int): Int
}

fun main() {
    println(Status.PENDING.canTransitionTo(Status.DONE))     // true
    println(Status.DONE.canTransitionTo(Status.ACTIVE))      // false (already final)

    println(Operation.MULTIPLY.apply(6, 7))                   // 42

    // Standard enum APIs
    println(Status.values().joinToString { it.label })
    println(Status.valueOf("ACTIVE"))
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.