Making Decisions
8 min · Scala
Run different code depending on whether something is true.
Enemy 1 of 5
if / else syntax
Programs need to act differently depending on the data they get. The if statement lets a program choose between paths instead of always running the same steps.
This code checks if temperature is greater than 20 and prints Warm or Cold. Since temperature is 5, press Run and look for Cold in the output.
Why this works
Every program so far has run the same instructions every time, in a straight line from top to bottom. Real programs need to behave differently depending on the data they're given: show a different message to a new user than a returning one, treat a negative number differently than a positive one, and so on. `if` is the tool that lets a program choose between two (or more) paths at runtime instead of always doing the same thing.
An `if` is followed by a condition in parentheses and a block in curly braces: `if (condition) { ... }`. If the condition evaluates to `true`, the block runs; if it's `false`, an optional `else { ... }` block runs instead. Conditions are built with comparison operators: `>` and `<` for greater-than/less-than, `>=` and `<=` for "or equal to", `==` for equality, and `!=` for "not equal."
A classic beginner trip-up coming from some other languages: Scala uses `==` for value equality on both primitives and objects (it's smart about it), so you don't need a separate `.equals` call the way you sometimes do elsewhere, but it's still easy to typo a single `=` (assignment) where you meant `==` (comparison), so double-check when something isn't branching the way you expect.