Kotlin Booleans
The Boolean type represents exactly two values, true and false, and forms the foundation of every decision your program makes.
Declaring Boolean Values
A Boolean variable in Kotlin can hold only true or false, with no implicit conversion from numbers or strings, unlike some other languages. This strictness prevents an entire category of accidental bugs.
Basic Boolean declarations
fun main() {
val isRaining = true
val isWeekend = false
println("Is it raining? $isRaining")
println("Is it the weekend? $isWeekend")
}Booleans from Comparisons
Most Boolean values in real programs come from evaluating an expression rather than being typed literally. Any comparison or logical expression automatically produces a Boolean result that can be stored, printed, or used directly in a condition.
Booleans produced by comparisons, used in if
fun main() {
val temperature = 38
val isHot = temperature > 30
val isFreezing = temperature < 0
println("Is it hot? $isHot")
println("Is it freezing? $isFreezing")
if (isHot) {
println("Remember to stay hydrated!")
}
}Booleans in Control Flow
- Conditions inside if / else branches
- Loop conditions in while and do-while loops
- Guard clauses that return early from a function
- Flags that track state, such as isLoggedIn or hasPermission
- Return types of predicate functions like isValid(input: String): Boolean
A Boolean-returning function used in a loop
fun isEven(number: Int): Boolean {
return number % 2 == 0
}
fun main() {
val values = listOf(4, 7, 10, 13)
for (value in values) {
val result = isEven(value)
println("$value is even: $result")
}
}Note: Tip: Prefer naming Boolean variables and functions so they read like a yes/no question, e.g. isValid, hasStock, canSubmit, rather than vague names like flag or check.
Note: Warning: There is no automatic conversion between Boolean and Int in Kotlin. Code like if (1) { ... }, which is valid in some languages, will not compile here; conditions must be actual Boolean expressions.
Exercise: Kotlin Booleans
What are the only two possible values of a Boolean in Kotlin?