Skip to Content
Course content
Click on the "Edit" button in the top corner of the screen to edit your slide content.

If you're coming from Java, C#, or JavaScript, you're probably looking at when and thinking, "Okay, this is just Kotlin's version of a switch statement." I've seen a lot of developers make this mistake early on, and while it seems harmless, it actually prevents you from writing truly idiomatic Kotlin.

The "Just a Switch" Fallacy

In most languages, a switch is a statement. It's a block of code that executes a side effect—like printing a line or updating a variable—but it doesn't "become" anything. You've probably written code like this a thousand times:

// The "Statement" mindset
var message = ""
when (status) {
    Status.Success -> message = "Operation worked!"
    Status.Error -> message = "Something went wrong."
    Status.Pending -> message = "Please wait..."
}

Technically, this works. But it's clunky. You're forced to declare a mutable variable (var) and then manually update it inside each branch. It's a pattern that invites bugs, especially as the logic grows. In Kotlin, when is an expression, meaning it returns a value. I almost always prefer assigning the result of the when block directly to a variable.

Treating Your Logic as a Value

Once you realize when returns a value, your code becomes cleaner and you can use val instead of var. This makes your data immutable and your intent much clearer. Let's look at that same status check, but written the way a professional Kotlin dev would do it:

val message = when (status) {
    Status.Success -> "Operation worked!"
    Status.Error -> "Something went wrong."
    Status.Pending -> "Please wait..."
}

See the difference? We've eliminated the boilerplate and the mutation. However, there's a catch: because the compiler needs to know exactly what message will be, the when expression must be exhaustive. If you're using an enum or a sealed class, the compiler is smart enough to know if you've covered every case. If you're using an Int or a String, you'll have to add an else branch to catch everything else. Trust me, don't fight the else branch—it's there to keep your app from crashing in production.

Moving Beyond Simple Equality

The real power of when kicks in when you stop using it just for simple equality checks. I love using it to replace long, nested if-else if chains. You can check for ranges, types, or even provide no argument at all to create a flexible conditional block.

Check out how we can handle a variety of different conditions in a single, readable block:

val priority = when (ticket) {
    is HighPriorityTicket -> "Immediate Action"
    is LowPriorityTicket -> "Backlog"
    in 1..5 -> "Critical Window" // Assuming ticket is also an Int
    "Urgent" -> "High Priority"
    else -> "Standard"
}

Notice the is keyword? That's smart casting. Inside that branch, Kotlin knows ticket is a HighPriorityTicket, so you can access its specific properties without casting it manually. It's a huge time-saver.




📋 Practical Task

Build a Subscription Feature Gate

You are building a feature-access system for a SaaS application. You need to determine what "Access Level" a user has based on their subscription plan and their account age (in months).

Requirements:

  • Create an enum called Plan with values: FREE, PRO, and ENTERPRISE.
  • Write a function getAccessLevel(plan: Plan, accountAgeMonths: Int): String.
  • Use a single when expression to return the following strings:
    • If the plan is ENTERPRISE: return "Full Access" regardless of age.
    • If the plan is PRO and the age is 12 months or more: return "Premium Loyalty Access".
    • If the plan is PRO but the age is less than 12: return "Standard Pro Access".
    • If the plan is FREE and the age is 24 months or more: return "Legacy Free Access".
    • For all other FREE users: return "Basic Access".

Hint: To handle the PRO and FREE logic, try using when without an argument and placing your boolean logic (e.g., plan == Plan.PRO && accountAgeMonths >= 12) inside the branches.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.