What && does
Sometimes one test isn't enough. You may want to run code only when the weather is sunny and the temperature is high. The logical and operator, written &&, joins two Boolean expressions into one. The result is true only when both sides are true. If either side is false, the whole expression is false.
| Left | Right | Left && Right |
|---|---|---|
true | true | true |
true | false | false |
false | true | false |
false | false | false |
Here is an example with two comparisons:
10 == 10 && 7 < 10 // true
The left side, 10 == 10, is true. The right side, 7 < 10, is also true. Both hold, so the whole line is true.
Using && in an if
In practice, && sits inside the condition of an if:
val x = 10
if (x != 7 && 12 < x) {
println("This is true!")
}
With x equal to 10, the first part x != 7 is true, but the second part 12 < x is false. One failure is enough to make the whole condition false, so the block is skipped and the program prints nothing.
Each side of && is a complete condition. Comparisons are evaluated before &&, so you don't need parentheses around them. You may chain more than two: a && b && c is true only when all three are.
Short-circuit evaluation
Kotlin evaluates && from left to right and stops as soon as the answer is known. If the left side is false, the result must be false, so the right side is never evaluated. This is called short-circuiting, and it makes some checks safe:
fun check(label: String, v: Boolean): Boolean {
println("checking $label")
return v
}
println(check("left", false) && check("right", true))
This prints checking left and then false. The function for the right side never runs. With true on the left, both checks run and the result is true.
The same rule lets you guard a risky test with a safe one. In list != null && list.size > 0, the size is only read when the list is not null. Kotlin even understands this: inside the right side, it treats list as non-null.
The exercise
You start with two variables:
val weather = "rainy"
val temperature = 90
The task has two steps.
- Write an
ifwith the conditionweather == "sunny" && temperature > 85, and print"Going to the beach"inside it. The message should only appear when both checks pass. In Kotlin,==on strings compares their text, soweather == "sunny"does what you expect. - Add an
elsebranch that prints"Learning to code", so the program still answers when either check fails.
val weather = "rainy"
val temperature = 90
if (weather == "sunny" && temperature > 85) {
println("Going to the beach")
} else {
println("Learning to code")
}
It's hot, but the weather is "rainy", so the left check fails and the program prints Learning to code. Change weather to "sunny" and it prints Going to the beach. Keep "sunny" but lower the temperature to 70 and the second check fails, so you are back to Learning to code.
Always test both sides of a rule like this one: the case where both parts hold, and the cases where only one of them does.
Keeping long conditions readable
When a condition grows, give each part a name. The names turn the if into a sentence:
val isSunny = weather == "sunny"
val isHot = temperature > 85
if (isSunny && isHot) {
println("Going to the beach")
}
The behaviour is the same as before. Each variable holds a Boolean, and && combines them. You can also split a long condition over several lines, as long as each line except the last ends with && so that Kotlin knows the expression continues.
Common mistakes
- A single
&. Kotlin doesn't use&for logical and. Use two. - Dropping the second comparison. Writing
weather == "sunny" && 85does not compile, because85is not aBoolean. Each side needs its own full comparison, such astemperature > 85. - Using
>=when the rule says more than. A temperature of exactly 85 must not go to the beach. - Mixing up the words. "Sunny and hot" needs
&&. Using the or operator||would let rainy days at 90 degrees through.
Key takeaways
a && bistrueonly when bothaandbaretrue.- Each side of
&&is its own complete condition. - If the left side is
false, the right side isn't evaluated. - Strings are compared with
==in Kotlin. - Naming the parts of a condition keeps long
ifstatements easy to read.