When building Android applications using Kotlin and Jetpack Compose, we often need to make decisions based on different conditions.
For example:
- Show a welcome message when a user logs in.
- Display an error message when a form is invalid.
- Enable a button when certain requirements are met.
- Show different screens based on application state.
- Display a different message depending on a user’s score.
- Handle loading, success, and error states.
Kotlin provides powerful conditional expressions to handle these situations.
The most commonly used are if, else, else if, and when.
In this tutorial, we’ll learn Kotlin conditional expressions with simple examples and see how to use them in real Android applications.
What You’ll Learn
By the end of this tutorial, you’ll understand:
- What conditional expressions are
- Kotlin
ifstatements - Kotlin
if-else - Kotlin
else ifchains - Using
ifas an expression - Nested
ifconditions - Combining conditions with logical operators
- Kotlin
whenexpressions whenwith multiple valueswhenwith rangeswhenwithout an argument- Kotlin
whenvsif-else - Conditional UI rendering in Jetpack Compose
- Common beginner mistakes
- Practical Kotlin exercises
Let’s begin!
1. What Are Conditional Statements in Kotlin?
Conditional statements allow a program to execute different code depending on whether a condition is true or false.
For example, consider an Android application that checks whether a user is old enough to access a feature.
val age = 20
if (age >= 18) {
println("Access Allowed")
}
Output:
Access Allowed
Here:
agestores the value 20.age >= 18checks whether the age is at least 18.- The condition evaluates to
true. - Kotlin executes the code inside the
ifblock.
Conditional logic is essential in almost every application.
2. Kotlin if Statement
The if statement executes a block of code only when its condition is true.
Syntax
if (condition) {
// Code executes when condition is true
}
Example
fun main() {
val temperature = 35
if (temperature > 30) {
println("It's a hot day")
}
}
Output:
It's a hot day
If the condition is false, Kotlin skips the block.
Another Example
val isLoggedIn = true
if (isLoggedIn) {
println("Welcome back!")
}
Output:
Welcome back!
Notice that Kotlin doesn’t require parentheses around the Boolean value itself beyond the if condition syntax.
3. Kotlin if-else Statement
The if-else statement executes one block when the condition is true and another block when it is false.
Syntax
if (condition) {
// True condition
} else {
// False condition
}
Example: Even or Odd Number
fun main() {
val number = 15
if (number % 2 == 0) {
println("Even Number")
} else {
println("Odd Number")
}
}
Output:
Odd Number
How It Works
The expression:
number % 2 == 0
checks whether the number is divisible by 2 without a remainder.
If the condition is true, the number is even.
Otherwise, the number is odd.
4. Kotlin else if Statement
Sometimes we need to evaluate multiple conditions.
Kotlin provides else if for this purpose.
Syntax
if (condition1) {
// First condition
} else if (condition2) {
// Second condition
} else {
// Default case
}
Example: Student Grade
fun main() {
val marks = 85
if (marks >= 90) {
println("Grade A+")
} else if (marks >= 75) {
println("Grade A")
} else if (marks >= 60) {
println("Grade B")
} else if (marks >= 40) {
println("Grade C")
} else {
println("Failed")
}
}
Output:
Grade A
Important
Kotlin evaluates the conditions from top to bottom.
Once a condition is true, the corresponding block executes, and the remaining branches are skipped.
Therefore, the order of conditions matters.
5. Kotlin if as an Expression
One of Kotlin’s useful features is that if can return a value.
Unlike traditional statement-only usage, Kotlin allows us to assign the result of an if-else expression directly to a variable.
Example
val age = 20
val result = if (age >= 18) {
"Adult"
} else {
"Minor"
}
println(result)
Output:
Adult
Shorter Version
val age = 20
val result = if (age >= 18) "Adult" else "Minor"
println(result)
This is useful when selecting one value based on a condition.
Practical Example
val isDarkMode = true
val themeName = if (isDarkMode) {
"Dark Theme"
} else {
"Light Theme"
}
println(themeName)
Output:
Dark Theme
When if is used as an expression that must produce a value, both the true and false paths need to provide a result.
6. Kotlin Nested if Statements
A nested if is an if statement placed inside another if statement.
Example
fun main() {
val isLoggedIn = true
val isPremium = true
if (isLoggedIn) {
if (isPremium) {
println("Premium Content Unlocked")
} else {
println("Upgrade to Premium")
}
} else {
println("Please Login")
}
}
Output:
Premium Content Unlocked
Nested conditions can be useful, but too many nested blocks make code difficult to read.
Whenever possible, simplify your conditions.
7. Combining Conditions Using Logical Operators
Kotlin allows multiple conditions to be combined using logical operators.
| Operator | Meaning | ||
|---|---|---|---|
&& | Logical AND | ||
| ` | ` | Logical OR | |
! | Logical NOT |
Example: AND Operator
val age = 25
val hasLicense = true
if (age >= 18 && hasLicense) {
println("Eligible to Drive")
} else {
println("Not Eligible")
}
Output:
Eligible to Drive
Both conditions must be true.
Example: OR Operator
val isAdmin = false
val isModerator = true
if (isAdmin || isModerator) {
println("Access Granted")
}
Output:
Access Granted
At least one condition must be true.
Example: NOT Operator
val isLoading = false
if (!isLoading) {
println("Content Ready")
}
Output:
Content Ready
These operators are especially useful for Android form validation and access control.
8. What Is Kotlin when Expression?
The when expression is a powerful alternative to long if-else chains.
It allows you to evaluate a value against multiple possible cases.
Syntax
when (value) {
option1 -> println("Option 1")
option2 -> println("Option 2")
else -> println("Default Option")
}
Example: Day of the Week
fun main() {
val day = 3
when (day) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
4 -> println("Thursday")
5 -> println("Friday")
6 -> println("Saturday")
7 -> println("Sunday")
else -> println("Invalid Day")
}
}
Output:
Wednesday
Kotlin evaluates the branches and executes the first matching branch.
9. Kotlin when as an Expression
Like if, Kotlin’s when can return a value.
Example
val day = 1
val dayName = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid Day"
}
println(dayName)
Output:
Monday
This approach is useful when mapping one value to another.
Android Example
val statusCode = 200
val message = when (statusCode) {
200 -> "Success"
400 -> "Bad Request"
401 -> "Unauthorized"
404 -> "Not Found"
500 -> "Server Error"
else -> "Unknown Status"
}
println(message)
Output:
Success
When used as an expression, when must cover all possible cases.
An else branch is commonly used to handle unmatched values, although it isn’t required when the compiler can establish that the branches are exhaustive.
10. Kotlin when with Multiple Values
Sometimes multiple values should produce the same result.
Kotlin allows you to combine multiple conditions in a single when branch.
Example
val day = 6
val dayType = when (day) {
1, 2, 3, 4, 5 -> "Weekday"
6, 7 -> "Weekend"
else -> "Invalid Day"
}
println(dayType)
Output:
Weekend
This is cleaner than repeating the same result for several branches.
11. Kotlin when with Ranges
Kotlin supports ranges inside when expressions.
Example: Grade Calculator
val marks = 85
val grade = when (marks) {
in 90..100 -> "A+"
in 75..89 -> "A"
in 60..74 -> "B"
in 40..59 -> "C"
in 0..39 -> "Fail"
else -> "Invalid Marks"
}
println(grade)
Output:
A
How It Works
The in operator checks whether the value belongs to a range.
For example:
in 75..89
matches values between 75 and 89, inclusive.
This makes when useful for grading, scoring, and category selection.
12. Kotlin when Without an Argument
Kotlin also supports when without a subject.
In this form, each branch contains a Boolean condition.
Example
val temperature = 32
val weather = when {
temperature >= 40 -> "Very Hot"
temperature >= 30 -> "Hot"
temperature >= 20 -> "Warm"
temperature >= 10 -> "Cool"
else -> "Cold"
}
println(weather)
Output:
Hot
This is a readable alternative to multiple else if conditions.
Important
Conditions are checked from top to bottom.
The first matching branch is selected.
13. Kotlin when with Strings
when expressions can also compare String values.
Example
val userRole = "admin"
val message = when (userRole) {
"admin" -> "Full Access"
"editor" -> "Edit Access"
"viewer" -> "Read Only"
else -> "Unknown Role"
}
println(message)
Output:
Full Access
This can be useful for mapping fixed application values to messages.
For more complex applications, enums or sealed types may provide stronger type safety than arbitrary strings.
14. Kotlin when with Enum Classes
Enums represent a fixed set of named constants.
Let’s create an enum for an application’s theme mode.
enum class ThemeMode {
LIGHT,
DARK,
SYSTEM
}
Now use when:
val selectedTheme = ThemeMode.DARK
val themeName = when (selectedTheme) {
ThemeMode.LIGHT -> "Light Theme"
ThemeMode.DARK -> "Dark Theme"
ThemeMode.SYSTEM -> "System Default"
}
println(themeName)
Output:
Dark Theme
Notice that we didn’t need an else branch.
This is because every possible enum value is handled.
This technique is commonly used in Android settings and state management.
15. Kotlin if-else vs when
Both if-else and when are useful for conditional logic.
| Feature | if-else | when |
|---|---|---|
| Simple Boolean condition | Excellent | Supported |
| Multiple conditions | Supported | Excellent |
| Match a value against cases | Supported | Excellent |
| Range matching | Supported | Excellent |
| Return a value | Yes | Yes |
| Exhaustive enum matching | Possible | Especially convenient |
| Common usage | Validation and branching | State and value matching |
When Should You Use if-else?
Use if-else when you have simple Boolean conditions.
Example:
val isLoggedIn = true
if (isLoggedIn) {
println("Welcome")
} else {
println("Please Login")
}
When Should You Use when?
Use when when you need to handle multiple distinct cases.
Example:
val screen = "profile"
when (screen) {
"home" -> println("Home Screen")
"profile" -> println("Profile Screen")
"settings" -> println("Settings Screen")
else -> println("Unknown Screen")
}
Choose whichever makes your code clearer.
16. Practical Android Example: Login Validation
Let’s build a simple login validation example using Kotlin conditions.
fun validateLogin(
email: String,
password: String
): String {
return when {
email.isBlank() -> "Email is required"
password.isBlank() -> "Password is required"
password.length < 8 -> "Password must have at least 8 characters"
else -> "Basic validation passed"
}
}
Usage
fun main() {
val result = validateLogin(
email = "user@example.com",
password = "password123"
)
println(result)
}
Output:
Basic validation passed
Important
This example demonstrates basic input validation only.
It does not authenticate a user, verify the email address, or guarantee password security.
Real authentication requires appropriate server-side verification and secure handling of credentials.
17. Conditional UI Rendering in Jetpack Compose
Jetpack Compose allows us to display different UI elements based on application state.
Let’s create a simple login-status screen.
Example
@Composable
fun LoginStatusScreen() {
var isLoggedIn by remember {
mutableStateOf(false)
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(24.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = if (isLoggedIn) {
"Welcome Back!"
} else {
"Please Login"
},
style = MaterialTheme.typography.headlineMedium
)
Spacer(
modifier = Modifier.height(24.dp)
)
Button(
onClick = {
isLoggedIn = !isLoggedIn
}
) {
Text(
text = if (isLoggedIn) {
"Logout"
} else {
"Login"
}
)
}
}
}
Required Imports
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
Expected UI
Initial state:
+--------------------------------+
| |
| Please Login |
| |
| [Login] |
| |
+--------------------------------+
After tapping Login:
+--------------------------------+
| |
| Welcome Back! |
| |
| [Logout] |
| |
+--------------------------------+
How It Works
The variable:
var isLoggedIn by remember {
mutableStateOf(false)
}
stores observable UI state.
When the button is clicked:
isLoggedIn = !isLoggedIn
the Boolean value changes.
Jetpack Compose observes the state change and recomposes the relevant UI.
The if-else expression determines which text appears.
This is a UI demonstration, not a real login implementation.
18. Jetpack Compose Example: UI States Using when
Real Android applications often have different UI states.
For example:
- Loading
- Success
- Error
Kotlin’s when expression works well for handling these states.
Define UI State
enum class UiState {
LOADING,
SUCCESS,
ERROR
}
Compose Example
@Composable
fun StatusScreen(
state: UiState
) {
when (state) {
UiState.LOADING -> {
CircularProgressIndicator()
}
UiState.SUCCESS -> {
Text(
text = "Data Loaded Successfully",
color = MaterialTheme.colorScheme.primary
)
}
UiState.ERROR -> {
Text(
text = "Something Went Wrong",
color = MaterialTheme.colorScheme.error
)
}
}
}
Required Imports
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
Usage
StatusScreen(
state = UiState.SUCCESS
)
Expected result:
Data Loaded Successfully
Why Use when Here?
Each UI state maps to a different UI component.
The when expression makes this mapping clear.
When used with enums or sealed types, exhaustive matching can also help catch missing cases as your application evolves.
We’ll explore advanced UI state management with ViewModel and StateFlow in future tutorials.
19. Common Kotlin Conditional Mistakes
Mistake 1: Using = Instead of ==
Incorrect:
var age = 18
if (age = 18) {
println("Adult")
}
Correct:
val age = 18
if (age == 18) {
println("Age is 18")
}
The = operator is for assignment.
The == operator checks equality.
Mistake 2: Incorrect Condition Order
Consider:
val marks = 95
if (marks >= 40) {
println("Pass")
} else if (marks >= 90) {
println("Excellent")
}
The second condition will never be reached for marks of 95 because the first condition is already true.
Correct:
if (marks >= 90) {
println("Excellent")
} else if (marks >= 40) {
println("Pass")
}
Always arrange overlapping conditions carefully.
Mistake 3: Missing else in a Non-Exhaustive Expression
Incorrect:
val age = 20
val result = if (age >= 18) {
"Adult"
}
A value-producing if expression needs a result for the false case.
Correct:
val result = if (age >= 18) {
"Adult"
} else {
"Minor"
}
Mistake 4: Unnecessary Nested Conditions
Avoid deeply nested code when a simpler expression works.
Instead of:
if (isLoggedIn) {
if (isPremium) {
println("Access Granted")
}
}
You can write:
if (isLoggedIn && isPremium) {
println("Access Granted")
}
Both examples assume the Boolean variables have already been defined.
Mistake 5: Using String Values for Every State
Avoid representing complex application states using arbitrary strings.
Instead of:
val state = "loading"
Consider:
enum class UiState {
LOADING,
SUCCESS,
ERROR
}
Enums and sealed types make application states easier to maintain.
20. Kotlin Conditional Expressions Quick Reference
| Concept | Syntax |
|---|---|
| Simple if | if (condition) { } |
| if-else | if (condition) { } else { } |
| else if | else if (condition) { } |
| if expression | val x = if (a > b) a else b |
| Logical AND | a && b |
| Logical OR | a || b |
| Logical NOT | !a |
| when expression | when (value) { ... } |
| Multiple cases | 1, 2, 3 -> "Match" |
| Range matching | in 1..10 -> "Valid" |
| when without subject | when { condition -> result } |
| Default branch | else -> "Unknown" |
21. Practical Exercises
Try these exercises to improve your Kotlin conditional programming skills.
Exercise 1: Positive, Negative, or Zero
Create a Kotlin program that checks whether a number is:
- Positive
- Negative
- Zero
Use if-else.
Exercise 2: Student Grade Calculator
Create a marks variable.
Use when to display:
- A+ for 90–100
- A for 75–89
- B for 60–74
- C for 40–59
- Fail for 0–39
Handle invalid marks as well.
Exercise 3: Simple Calculator
Create two numbers and an operator.
Use when to perform:
- Addition
- Subtraction
- Multiplication
- Division
Handle division by zero.
Exercise 4: User Access Validation
Create:
val isLoggedIn = true
val isPremium = false
Display:
- “Premium Access” when both are true.
- “Upgrade Required” when logged in but not premium.
- “Please Login” when not logged in.
Exercise 5: Jetpack Compose Status Screen
Create a Compose screen with three buttons:
- Loading
- Success
- Error
Use when to display different content based on the selected state.
What We’ve Learned
In this tutorial, we learned:
- What conditional statements and expressions are
- How Kotlin
ifworks - How to use
if-else - How to handle multiple conditions using
else if - How
ifreturns values - How nested conditions work
- How to combine logical conditions
- How Kotlin
whenworks - How to use multiple values and ranges in
when - How to use
whenwithout an argument - How to use enums with
when - Differences between
if-elseandwhen - Conditional UI rendering in Jetpack Compose
- Common beginner mistakes
Conditional expressions are essential for implementing business logic, validation, navigation decisions, and dynamic UI behavior in Android applications.
What’s Next?
In our next tutorial, we’ll explore:
Kotlin Loops Explained: for, while, do-while, break & continue
You’ll learn:
- Kotlin
forloops - Kotlin
whileloops - Kotlin
do-whileloops - Iterating through ranges
- Iterating through collections
breakandcontinue- Nested loops
- Practical Kotlin examples
- Common beginner mistakes
Happy Coding!
Continue learning modern Android development with Moiks Developer Blog.