Booleans and Comparisons
Prerequisites: Basic types and type inference
A Boolean is a yes/no value: true or false. Comparisons produce
Booleans:
fun main() {
val age = 20
println(age > 18)
println(age == 21)
println(age != 21)
println("kotlin" == "kotlin")
println("apple" < "banana")
println("Ada".equals("ada", ignoreCase = true))
}
true
false
true
true
true
true
| Operator | Meaning |
|---|---|
== |
equal to |
!= |
not equal to |
> < |
greater / less than |
>= <= |
greater / less or equal |
Strings compare alphabetically with < and >.
Only Boolean is a condition
A condition must be an actual Boolean. Numbers and strings are never
treated as true or false:
fun main() {
val count = 3
if (count) {
println("has items")
}
}
error: condition type mismatch: inferred type is 'Int' but 'Boolean' was expected.
Write what you mean: if (count > 0), if (name.isNotEmpty()).
Name Boolean variables so they read as yes/no questions: isEnabled,
hasAccount, canEdit.