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) }
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 }
}
}
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>
}
Exhaustive When
fun getTitle(screen: Screen): String = when (screen) {
Screen.HOME -> "Home"
Screen.SEARCH -> "Search"
Screen.PROFILE -> "Profile"
}
JSON Serialization
@Serializable
enum class Role {
@SerialName("admin") ADMIN,
@SerialName("user") USER,
@SerialName("guest") GUEST
}
Summary
- Type-safe constants with
enum class - Properties, functions, companion objects for logic
- Exhaustive
whenchecks prevent missing cases - Room and kotlinx-serialization integration
8 production-ready Android app templates on Gumroad.
Browse templates → Gumroad
Top comments (0)