Skip to main content

Kotlin If Else

In programming, we often need to make decisions based on certain conditions. Kotlin's if-else statements allow your program to execute different blocks of code depending on whether a condition is true or false. This fundamental control flow concept is essential for creating dynamic and responsive applications.

Basic If Statement

The most basic form of conditional execution is the if statement, which runs a block of code only if a specified condition evaluates to true.

kotlin
fun main() {
val temperature = 28

if (temperature > 25) {
println("It's a hot day!")
}
}

Output:

It's a hot day!

In this example, since the temperature (28) is greater than 25, the message is displayed. If the temperature had been 25 or lower, nothing would have been printed.

If-Else Statement

To provide an alternative action when the condition is false, we use an if-else statement.

kotlin
fun main() {
val temperature = 15

if (temperature > 25) {
println("It's a hot day!")
} else {
println("It's not hot today.")
}
}

Output:

It's not hot today.

Since the temperature is 15, which is not greater than 25, the else block executes.

If-Else If-Else Chain

For more complex decisions with multiple conditions, we can use an if-else if-else chain.

kotlin
fun main() {
val temperature = 15

if (temperature > 30) {
println("It's very hot today!")
} else if (temperature > 20) {
println("It's warm today.")
} else if (temperature > 10) {
println("It's cool today.")
} else {
println("It's cold today!")
}
}

Output:

It's cool today.

In this example, Kotlin checks each condition in sequence. Since the temperature is 15, it matches the condition temperature > 10, so "It's cool today." gets printed.

If as an Expression

One of Kotlin's powerful features is that if can be used as an expression that returns a value. This is similar to the ternary operator in other languages.

kotlin
fun main() {
val temperature = 28

val message = if (temperature > 25) {
"It's hot today!"
} else {
"It's not hot today."
}

println(message)
}

Output:

It's hot today!

The if-else expression evaluates to either "It's hot today!" or "It's not hot today." based on the condition, and that value is assigned to the message variable.

Simplified Expression Syntax

For simple expressions, you can write them more concisely:

kotlin
val message = if (temperature > 25) "It's hot today!" else "It's not hot today."

This achieves the same result as the previous example.

Nested If Statements

You can also nest if statements inside each other for more complex decision-making.

kotlin
fun main() {
val temperature = 28
val isRaining = true

if (temperature > 25) {
println("It's hot today!")

if (isRaining) {
println("It's hot and rainy - it might be humid.")
} else {
println("It's hot but not raining - stay hydrated!")
}
} else {
println("It's not hot today.")

if (isRaining) {
println("It's cool and rainy - take an umbrella!")
} else {
println("It's cool and dry - perfect weather!")
}
}
}

Output:

It's hot today!
It's hot and rainy - it might be humid.

While nesting is powerful, avoid excessive nesting as it can make your code harder to read and maintain.

Logical Operators with If Statements

You can combine multiple conditions using logical operators:

  • && (AND): Both conditions must be true
  • || (OR): At least one condition must be true
  • ! (NOT): Inverts a boolean result
kotlin
fun main() {
val temperature = 28
val isRaining = true

if (temperature > 25 && isRaining) {
println("It's hot and rainy - it might be humid.")
} else if (temperature > 25 || isRaining) {
println("Either it's hot or it's raining (or both).")
} else {
println("It's neither hot nor rainy.")
}
}

Output:

It's hot and rainy - it might be humid.

Real-World Example: Simple Weather App

Let's build a simple function that provides clothing recommendations based on weather conditions:

kotlin
fun getClothingRecommendation(temperature: Int, isRaining: Boolean, isWindy: Boolean): String {
return if (temperature > 30) {
if (isRaining) {
"Wear light clothes and take an umbrella."
} else {
"Wear light clothes, apply sunscreen, and take water."
}
} else if (temperature > 20) {
if (isRaining) {
"A light jacket and umbrella would be good."
} else if (isWindy) {
"A light jacket is recommended due to the wind."
} else {
"A t-shirt should be fine."
}
} else if (temperature > 10) {
if (isRaining && isWindy) {
"Wear a waterproof jacket and warm clothes."
} else if (isRaining) {
"Take a jacket and umbrella."
} else {
"A jacket or sweater should be enough."
}
} else {
if (isRaining || isWindy) {
"Wear a heavy coat, and take an umbrella if it's raining."
} else {
"Wear a warm coat today."
}
}
}

fun main() {
val currentTemp = 22
val isRaining = true
val isWindy = false

val recommendation = getClothingRecommendation(currentTemp, isRaining, isWindy)
println("Weather advice: $recommendation")
}

Output:

Weather advice: A light jacket and umbrella would be good.

Summary

Kotlin's if-else statements provide a flexible way to control the flow of your program based on conditions:

  • Simple if: Execute code only if a condition is true
  • if-else: Execute one block if the condition is true, another if it's false
  • if-else if-else chains: Test multiple conditions in sequence
  • if as an expression: Return values based on conditions (replacing ternary operators)
  • Nested if statements: Create complex decision trees
  • Logical operators: Combine multiple conditions for complex logic

Remember to keep your conditions clear and avoid overly complex nesting to keep your code readable.

Practice Exercises

  1. Write a program that determines if a number is positive, negative, or zero.
  2. Create a function that returns the maximum of three numbers using if-else expressions.
  3. Implement a simple login system that checks if a username and password match predefined values.
  4. Write a program that categorizes a person into age groups (child, teenager, adult, senior) based on their age input.
  5. Create a grade calculator that assigns letter grades (A, B, C, D, F) based on a numerical score.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)