Kotlin Conditional Statements
In programming, we often need to execute certain blocks of code based on specific conditions. This is where conditional statements come into play. Kotlin provides elegant and powerful ways to implement decision-making in your code through conditional statements.
Introduction to Conditional Statements
Conditional statements allow your program to make decisions and execute different code blocks based on whether certain conditions are true or false. In Kotlin, there are two main types of conditional constructs:
- if-else expressions
- when expressions (similar to switch statements in other languages, but more powerful)
Let's explore each of these in detail.
If-Else Expressions
The if-else
expression is one of the most fundamental conditional statements in Kotlin. Unlike many other languages where if
is a statement, in Kotlin, it's an expression that can return a value.
Basic If Statement
Here's the simplest form of an if
statement:
fun main() {
val temperature = 28
if (temperature > 25) {
println("It's warm outside!")
}
}
Output:
It's warm outside!
If-Else Statement
When you want to execute a different block of code when the condition is false:
fun main() {
val temperature = 18
if (temperature > 25) {
println("It's warm outside!")
} else {
println("It's not very warm today.")
}
}
Output:
It's not very warm today.
If-Else If-Else Chain
For multiple conditions, you can chain if-else
statements:
fun main() {
val temperature = 15
if (temperature > 30) {
println("It's hot outside!")
} else if (temperature > 20) {
println("It's warm outside!")
} else if (temperature > 10) {
println("It's cool outside!")
} else {
println("It's cold outside!")
}
}
Output:
It's cool outside!
If as an Expression
One of Kotlin's powerful features is that if
can be used as an expression that returns a value:
fun main() {
val temperature = 28
val message = if (temperature > 25) {
"It's warm outside!"
} else {
"It's not very warm today."
}
println(message)
}
Output:
It's warm outside!
You can also write this more concisely:
fun main() {
val temperature = 28
val message = if (temperature > 25) "It's warm outside!" else "It's not very warm today."
println(message)
}
When Expression
The when
expression in Kotlin is a more powerful version of the switch statement found in other languages. It can be used with both discrete values and arbitrary conditions.
Basic When Expression
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
Multiple Values in a Single Branch
You can combine multiple values in a single branch:
fun main() {
val day = 6
when (day) {
1, 2, 3, 4, 5 -> println("Weekday")
6, 7 -> println("Weekend")
else -> println("Invalid day")
}
}
Output:
Weekend
Using Ranges and Expressions
You can use ranges and more complex expressions in when
branches:
fun main() {
val score = 85
when (score) {
in 90..100 -> println("Excellent")
in 80..89 -> println("Good")
in 70..79 -> println("Average")
in 60..69 -> println("Below average")
else -> println("Failed")
}
}
Output:
Good
When Without Argument
when
can also be used without an argument, which makes it work like a series of if-else if
statements:
fun main() {
val temperature = 28
when {
temperature > 30 -> println("It's hot outside!")
temperature > 25 -> println("It's warm outside!")
temperature > 15 -> println("It's cool outside!")
else -> println("It's cold outside!")
}
}
Output:
It's warm outside!
When as an Expression
Like if
, when
can also be used as an expression that returns a value:
fun main() {
val month = 4
val season = when (month) {
12, 1, 2 -> "Winter"
in 3..5 -> "Spring"
in 6..8 -> "Summer"
in 9..11 -> "Fall"
else -> "Invalid month"
}
println("The season is $season")
}
Output:
The season is Spring
Real-World Applications
Let's look at some practical examples of how conditional statements are used in real applications:
User Authentication
fun main() {
val username = "user123"
val password = "pass123"
// Simulate database values
val correctUsername = "user123"
val correctPassword = "pass123"
if (username == correctUsername && password == correctPassword) {
println("Authentication successful!")
} else if (username != correctUsername) {
println("Unknown username")
} else {
println("Invalid password")
}
}
Output:
Authentication successful!
Simple Calculator
fun main() {
val num1 = 10.0
val num2 = 5.0
val operation = "+"
val result = when (operation) {
"+" -> num1 + num2
"-" -> num1 - num2
"*" -> num1 * num2
"/" -> if (num2 != 0.0) num1 / num2 else "Error: Division by zero"
else -> "Unknown operation"
}
println("Result: $result")
}
Output:
Result: 15.0
Weather App Recommendations
fun main() {
val temperature = 28
val isRaining = false
val recommendation = when {
isRaining -> "Take an umbrella!"
temperature > 30 -> "It's hot! Wear light clothes and stay hydrated."
temperature > 20 -> "Nice weather! Enjoy your day outside."
temperature > 10 -> "It's a bit cool. Consider wearing a light jacket."
else -> "It's cold outside. Wear warm clothes."
}
println(recommendation)
}
Output:
Nice weather! Enjoy your day outside.
Best Practices for Conditional Statements
- Use
when
instead of complex if-else chains - It's more readable and maintainable. - Take advantage of Kotlin's expression-oriented nature - Use if and when expressions to assign values.
- Keep conditionals simple - If your conditional logic becomes too complex, consider refactoring into multiple functions.
- Always include an
else
branch - Especially when using conditionals as expressions. - Use compound conditions with caution - Very complex conditions can reduce readability.
Summary
In this lesson, we explored Kotlin's conditional statements:
- if-else expressions: Basic conditionals that can also return values
- when expressions: Powerful pattern matching that can replace complex if-else chains
Kotlin's conditional statements are expressions rather than just statements, allowing them to return values. This feature makes your code more concise and often more readable.
Remember that the when
expression is one of Kotlin's most powerful features, offering much more flexibility than traditional switch statements in other languages.
Exercises
To practice what you've learned:
- Write a program that converts a numerical grade (0-100) into a letter grade (A, B, C, D, F) using if-else expressions.
- Create a program that takes a month number (1-12) as input and returns the number of days in that month using a when expression.
- Build a simple text-based adventure game that uses conditional statements to navigate the story based on user input.
- Implement a function that determines whether a year is a leap year using when without an argument.
- Create a BMI calculator that categorizes the result using conditional statements (underweight, normal, overweight, etc.).
Additional Resources
- Kotlin Official Documentation: Control Flow
- Kotlin by Example: Conditionals
- Kotlin Playground - Try out different conditional statements online
Now that you understand Kotlin's conditional statements, you're ready to implement decision-making logic in your programs. In the next lesson, we'll explore Kotlin loops and iterations.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)