DEV Community

myougaTheAxo
myougaTheAxo

Posted on

Kotlin Enum Class Patterns — Properties, Functions & Serialization

What You'll Learn

Practical Kotlin enum class patterns with properties, functions, serialization, and Compose integration.

Basic Enum

enum class Priority { LOW, MEDIUM, HIGH, URGENT }
val p = Priority.HIGH
println(p.name)    // HIGH
println(p.ordinal) // 2
Priority.entries.forEach { println(it) }
Enter fullscreen mode Exit fullscreen mode

Enum with Properties

enum class HttpStatus(val code: Int, val message: String) {
    OK(200, "OK"),
    NOT_FOUND(404, "Not Found"),
    INTERNAL_ERROR(500, "Internal Server Error");
    val isError: Boolean get() = code >= 400
    companion object {
        fun fromCode(code: Int) = entries.find { it.code == code }
    }
}
Enter fullscreen mode Exit fullscreen mode

Abstract Methods

enum class SortOrder {
    ASCENDING { override fun <T : Comparable<T>> sort(list: List<T>) = list.sorted() },
    DESCENDING { override fun <T : Comparable<T>> sort(list: List<T>) = list.sortedDescending() };
    abstract fun <T : Comparable<T>> sort(list: List<T>): List<T>
}
Enter fullscreen mode Exit fullscreen mode

Exhaustive When

fun getTitle(screen: Screen): String = when (screen) {
    Screen.HOME -> "Home"
    Screen.SEARCH -> "Search"
    Screen.PROFILE -> "Profile"
}
Enter fullscreen mode Exit fullscreen mode

JSON Serialization

@Serializable
enum class Role {
    @SerialName("admin") ADMIN,
    @SerialName("user") USER,
    @SerialName("guest") GUEST
}
Enter fullscreen mode Exit fullscreen mode

Summary

  • Type-safe constants with enum class
  • Properties, functions, companion objects for logic
  • Exhaustive when checks prevent missing cases
  • Room and kotlinx-serialization integration

8 production-ready Android app templates on Gumroad.
Browse templatesGumroad

Top comments (0)