All lessons

Making Decisions

8 min · Kotlin

Run different code depending on whether something is true.

Kotlin · Making Decisions0/5 cleared

Enemy 1 of 5

Almost every real program needs to make choices: only apply a discount if the cart total is over some threshold, only allow login if the password matches, and so on. Kotlin builds that decision-making with if. An if checks a condition — an expression that evaluates to true or false — and runs the code inside its { } block only when the condition is true.

Pairing if with else gives you a fallback for when the condition is false: exactly one of the two blocks runs, never both, never neither. You compare values with operators like > , < , and == (double equals for comparison, since a single = is reserved for assignment — mixing the two up is one of the most common beginner mistakes in almost every C-family language, though Kotlin's compiler will flag most misuses since if expects a Boolean, not an assignment).

Unlike Rust, Kotlin does require parentheses around the if condition — if (temperature > 20) { ... } — which matches Java, JavaScript, and C. The curly braces are technically optional for a single-statement block in Kotlin, but including them consistently, as the examples here do, avoids a classic bug where an unindented line silently falls outside the block you meant it to be in.

You
Memory-Leak Rat

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: Cold