Introduction to Conditional Statements

Welcome! Today, we'll dive into the world of conditional statements in programming. Let's start with a real-life example. Consider a traffic light: it displays different colors to control traffic flow — if it's green, the cars move. However, if it's red, they stop. Programming languages, like Kotlin, use conditional statements to control the execution flow similarly.

In Kotlin, we use the if and when expressions to make decisions. Consider a simple if statement:

var lightColor = "green"
if (lightColor == "green") {
    println("Cars can go.") // Output: "Cars can go."
} else {
    println("Cars should stop.")
}
Understanding the "if" Expression

In Kotlin, the if statement checks a condition and runs a specific code block if the condition is true — quite like making the decision to take an umbrella based on whether it's raining or not.

Take a look at the example where we verify whether a person with an age of 20 is an adult:

val age = 20
if (age >= 18) {
    println("You are an adult.") // Output: "You are an adult."
}

The message "You are an adult." gets printed because our age, which is 20, is greater than 18.

"If-else" and "if-else-if-else" Constructs

In Kotlin, the if-else and if-else-if-else constructs allow for conditional execution of code blocks based on certain conditions. For instance, consider a game where participants win a prize if they score more than 70 points. Those scoring 70 or less do not win a prize. This is handled by an if-else construct:

val score = 65
if (score > 70) {
    println("Congratulations! You've won a prize.")
} else {
    println("Better luck next time. Keep practicing.") // Output: "Better luck next time. Keep practicing."
}

// In a more complex scenario with multiple conditions, such as a quiz game awarding different prizes (bronze, silver, gold) based on scores, the `if-else-if-else` structure is used:
if (score > 90) {
    println("Congratulations! You've won a gold prize.")
} else if (score > 80) {
    println("Congratulations! You've won a silver prize.") // Only this print statement will be executed
} else if (score > 70) {
    println("Congratulations! You've won a bronze prize.")
} else {
    println("You've won a participation prize. Keep practicing.")
}

This demonstrates how Kotlin evaluates multiple conditions in an if-else-if-else structure, selecting the first true condition and ignoring the rest. It ensures efficient decision-making in code by not evaluating subsequent conditions once a match is found.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal