Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
7: When Expressions
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
Planwith values:FREE,PRO, andENTERPRISE. - Write a function
getAccessLevel(plan: Plan, accountAgeMonths: Int): String. - Use a single
whenexpression to return the following strings:- If the plan is
ENTERPRISE: return "Full Access" regardless of age. - If the plan is
PROand the age is 12 months or more: return "Premium Loyalty Access". - If the plan is
PRObut the age is less than 12: return "Standard Pro Access". - If the plan is
FREEand the age is 24 months or more: return "Legacy Free Access". - For all other
FREEusers: return "Basic Access".
- If the plan is
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.
There are no comments for now.