🧭 Enums in Kotlin β€” The Smartest Way to Represent Choices

When building Android apps, you constantly deal with choices:

  • User can be Free, Pro, or Admin
  • App theme can be Light or Dark
  • API call can be Loading, Success, or Error

You could represent these with Strings or integers…
…but then you end up debugging nonsense like "admni" or status = 5.

Kotlin gives a cleaner, safer alternative: Enums.


🧩 What Exactly Is an Enum?

An enum (enumeration) defines a type that can have one value from a predefined set.

Basic example:

enum class UserType {
    FREE,
    PRO,
    ADMIN
}

Using it:

val userType: UserType = UserType.PRO

Enums prevent invalid values β€” no more string typos!


🌟 Why Use Enums Instead of Strings or Ints?

Let’s compare:

// ❌ Bad:
val type = "admni" // typo β€” but compiles!

Versus:

// βœ… Good:
val type = UserType.ADMIN // safe, type-checked

With enums you get:

  • βœ”οΈ Type safety
  • βœ”οΈ Better IDE autocomplete
  • βœ”οΈ Cleaner code
  • βœ”οΈ Compile-time error for invalid values
  • βœ”οΈ Perfect integration with when{} expressions

🧱 Creating an Enum in Kotlin

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

Using when:

when (dir) {
    Direction.NORTH -> println("Going up")
    Direction.SOUTH -> println("Going down")
    Direction.EAST  -> println("Going right")
    Direction.WEST  -> println("Going left")
}

You must handle all possible values β€” which prevents bugs.


βš™οΈ Enums with Properties

Enums can store extra information.

Example: Weekend vs Weekday:

enum class DayType(val isWeekend: Boolean) {
    MONDAY(false),
    TUESDAY(false),
    WEDNESDAY(false),
    THURSDAY(false),
    FRIDAY(false),
    SATURDAY(true),
    SUNDAY(true)
}

Usage:

if (day.isWeekend) {
    println("Weekend! πŸŽ‰")
} else {
    println("Workday πŸ˜…")
}

🧠 Enums with Functions

You can add methods to enums β€” powerful for logic grouping.

enum class Operation {
    ADD, SUBTRACT, MULTIPLY, DIVIDE;

    fun apply(a: Int, b: Int): Int = when (this) {
        ADD      -> a + b
        SUBTRACT -> a - b
        MULTIPLY -> a * b
        DIVIDE   -> a / b
    }
}

Using it:

println(Operation.MULTIPLY.apply(4, 5)) // 20

🎨 Using Enums in Jetpack Compose β€” Real App Examples

Compose loves enums β€” they make UI states predictable and readable.


1️⃣ Theme Mode Enum

enum class AppThemeMode {
    LIGHT,
    DARK
}

Compose usage:

@Composable
fun ThemedScreen(themeMode: AppThemeMode) {
    val bg = when (themeMode) {
        AppThemeMode.LIGHT -> Color.White
        AppThemeMode.DARK  -> Color(0xFF121212)
    }

    Box(
        modifier = Modifier.fillMaxSize().background(bg),
        contentAlignment = Alignment.Center
    ) {
        Text("Theme: $themeMode")
    }
}

2️⃣ Screen State Enum (Loading, Content, Error)

enum class ScreenState {
    LOADING,
    CONTENT,
    ERROR
}

Compose UI:

@Composable
fun ProfileScreen(state: ScreenState) {
    when (state) {
        ScreenState.LOADING -> CircularProgressIndicator()
        ScreenState.CONTENT -> Text("Profile Loaded 😎")
        ScreenState.ERROR   -> Text("Error!", color = Color.Red)
    }
}

This pattern is extremely common in Android apps.


3️⃣ Button Style Enum

Define reusable styles:

enum class AppButtonStyle {
    PRIMARY,
    SECONDARY,
    DESTRUCTIVE
}

Compose button:

@Composable
fun AppButton(text: String, style: AppButtonStyle, onClick: () -> Unit) {
    val bg = when (style) {
        AppButtonStyle.PRIMARY     -> Color(0xFF2962FF)
        AppButtonStyle.SECONDARY   -> Color.LightGray
        AppButtonStyle.DESTRUCTIVE -> Color(0xFFD50000)
    }

    Button(onClick, colors = ButtonDefaults.buttonColors(containerColor = bg)) {
        Text(text)
    }
}

βš–οΈ Enums vs Sealed Classes β€” When Should You Use What?

Use CaseEnumSealed Class
Fixed set of valuesβœ… Yes⚠️ Not needed
Simple statesβœ… YesOptional
Values need propertiesβœ… YesOptional
Each state needs unique data❌ Noβœ… Yes
Used heavily in Compose UI stateβœ”οΈ Oftenβœ”οΈ Often

Quick rule:

πŸ‘‰ Use enums when the options are simple and constant.
πŸ‘‰ Use sealed classes when each option needs different data or behavior.


🧹 Best Practices for Using Enums

Here are some simple tips:

βœ”οΈ Use ALL_CAPS for enum constants

enum class NetworkType { WIFI, MOBILE, NONE }

βœ”οΈ Prefer enums for fixed modes or roles

Themes, filters, states, user roles.

βœ”οΈ Use when expressions for clarity

when (type) { ... }

βœ”οΈ Keep logic lightweight

Don’t overload enums with big functions.


🏁 Conclusion: Enums Keep Your Kotlin Code Clean and Safe

Enums are one of the simplest yet most powerful features in Kotlin. They help you:

  • Remove hardcoded strings
  • Make UI states easier to manage
  • Keep Compose screens predictable
  • Prevent bugs before they happen

If you’re building Android apps, enums will quickly become one of your favorite tools.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *