Lesson 7

Making Decisions in Kotlin: Conditional Logic with If and When Expressions

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:

1var lightColor = "green" 2if (lightColor == "green") { 3 println("Cars can go.") // Output: "Cars can go." 4} else { 5 println("Cars should stop.") 6}
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:

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

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:

1val score = 65 2if (score > 70) { 3 println("Congratulations! You've won a prize.") 4} else { 5 println("Better luck next time. Keep practicing.") // Output: "Better luck next time. Keep practicing." 6} 7 8// 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: 9if (score > 90) { 10 println("Congratulations! You've won a gold prize.") 11} else if (score > 80) { 12 println("Congratulations! You've won a silver prize.") // Only this print statement will be executed 13} else if (score > 70) { 14 println("Congratulations! You've won a bronze prize.") 15} else { 16 println("You've won a participation prize. Keep practicing.") 17}

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.

Utilizing `if-else` as an Expression

A powerful feature of Kotlin is using if-else as an expression, which allows it to return a value. This capability makes your code more concise and expressive, especially when assigning the result of a conditional check directly to a variable. Let's explore how this works:

1val age = 20 2val status = if (age >= 18) "adult" else "minor" 3println("You are an $status.") // Output: "You are an adult."

In this example, the if-else expression evaluates a condition and directly assigns the result to a variable. This approach streamlines code that requires conditional logic for variable assignment, enhancing readability and reducing verbosity.

Introduction to the "when" Expression

The when expression in Kotlin allows for concise and readable conditional logic. It evaluates conditions in sequence and executes the code block for the first matching branch. For instance, in a scenario where prizes are awarded based on quiz scores, the when expression can efficiently determine the prize:

1val score = 95 2when { 3 score > 90 -> println("Congratulations! You've won a gold prize.") // This branch matches, so its code is executed. 4 score > 80 -> println("Great! You've won a silver prize.") 5 score > 70 -> println("Good job! You've won a bronze prize.") 6 else -> println("You've won a participation prize. Keep practicing.") // This branch is the default action. 7}

This ensures that as soon as a condition is met, the corresponding action is taken without evaluating further conditions, making when an effective tool for handling multiple conditional paths in Kotlin.

Although we can achieve the same outcome with multiple if statements, the when expression optimizes this syntax. Therefore, when dealing with multiple possible results, a when expression is easier to write and more readable in Kotlin.

"when" Expression with Multiple Branches

Kotlin allows us to define multiple conditions within a single branch of a when expression:

1val score = 85 2val participantNumber = 1000 3when { 4 score > 90 || participantNumber == 1000 -> println("Congratulations! You've won a grand prize.") // Output: "Congratulations! You've won a grand prize." 5 score > 70 -> println("Good job! You've won a silver prize.") 6 else -> println("You've won a participation prize. Keep practicing.") 7}

In this example, the participant won the grand prize because they're the 1000th participant.

Using `when` with Predefined Values

In Kotlin, you can use the when expression to directly compare a variable against predefined values or conditions. This approach simplifies the process of performing different actions based on specific matches. For example, to check whether a number is odd or even, you can use when as follows:

1val number = 4 2val remainder = number % 2 // Holds 0, as 4 is divisible by 2 3 4when (remainder) { 5 0 -> println("$number is even") 6 1 -> println("$number is odd") 7 // You can add more branches here if needed 8 else -> println("This is an unexpected case") 9}

In this code, remainder stores the result of number % 2. The when expression then evaluates remainder, matching it with its predefined branches to determine and print whether the number is odd or even. This approach not only makes the code more understandable but also allows for easier modifications to the logic if needed.

`when` as an Expression

In Kotlin, the when construct goes beyond just controlling flow; it can also be used as an expression to return values. This allows for clean and concise assignments based on complex conditions:

1val status = 85 2val result = when { 3 status >= 0 && status <= 59 -> "Fail" 4 status >= 60 && status <= 79 -> "Pass" 5 else -> "Excellent" 6} 7println("Result: $result") // Output: "Result: Excellent"

This feature streamlines your Kotlin code by enabling direct value assignment from when, making your conditional logic both powerful and elegant.

Lesson Summary

You've mastered the if and when expressions in Kotlin. Both constructs can be used to make well-informed decisions and control flow in your Kotlin programs. Next on the agenda are some hands-on exercises for you to practice. Remember, practicing programming is the key to mastery! You're doing great, so keep it up!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.