3 min read
Booleans and Comparisons
Prerequisites: Numbers and math
@main def booleans(): Unit =
val age = 20
val hasTicket = true
println(age >= 18)
println(age == 21)
println(age != 21)
println(age >= 18 && hasTicket)
println(age < 13 || age > 65)
println(!hasTicket)
true
false
true
true
false
false
| Operator | Meaning |
|---|---|
==, != |
equal, not equal (compares values, even for strings and collections) |
<, <=, >, >= |
ordering |
&&, || |
and, or — short-circuit: the right side runs only if needed |
! |
not |
Equality compares values
@main def equality(): Unit =
println(List(1, 2, 3) == List(1, 2, 3))
println("abc" == "ab" + "c")
println(1 == 1.0)
true
true
true
Scala's == means "has the same value" for strings, collections, and case
classes. (For the rare case where you need "is the same object", there's
eq.)
Ranges of values
@main def between(): Unit =
val score = 72
println(score >= 50 && score <= 100)
println((1 to 10).contains(score))
true
false