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:
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:
The message "You are an adult." gets printed because our age, which is 20, is greater than 18.
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:
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.
