TL ; DR:
ifstatements allow us to build programs that can make decisions based on some conditions. Here is the syntax:val isRainy = true if(isRainy) { println("I bring an umbrella") }
Full lesson:
As humans, we often make decisions based on conditions. For example, we might go through these decision-making processes during a day:
If it's rainy:
I bring an umbrella
If I'm hungry:
I have breakfast
I I'm tired:
I take a nap
We can also tell the computer to make decisions like these in our programs.
If Statements:
if statements allow us to build programs that can make decisions based on some conditions. Here is the syntax:
if(conditions) {
// instructions
}
The keyword if tells Scala to execute the code inside the curly braces (where we have our Scala comment) only if the conditions defined in the parentheses are met.
Boolean conditions:
The conditions inside if statements are known as Boolean conditions and they may only be true or false.
If the Boolean condition evaluates to true, the program executes the statements inside curly braces. If it evaluates to false, the statements will not execute.
If you check our example, you'll see that all the conditions there (it's rainy, I'm hungry and I'm tired) are Boolean conditions.
Let's turn those decisions into working code using if statements:
val isRainy = true
if(isRainy) {
println("I bring an umbrella")
}
The code above prints "I bring an umbrella" since the condition in the parentheses evaluates to true
But this code:
val amHungry = false
if(amHungry) {
println("I have breakfast")
}
prints nothing since amHungry evaluates to false.
Assignment
Follow the Coding Tutorial and let's practice with if statements!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.