Kotlin Booleans
Programs constantly ask yes/no questions: Is the user logged in? Is the cart empty? Is the password long enough? The answers are values of type Boolean, which has exactly two possible values: true and false.
Boolean values
fun main() {
val isRaining: Boolean = false
val hasUmbrella = true // inferred as Boolean
println(isRaining)
println(hasUmbrella)
}false
true
Tip: Name Boolean variables so they read like a question:
isOpen,hasAccess,canRetry,shouldSave. Code likeif (isOpen)then reads like English.
Boolean expressions
Comparison operators produce Booleans, so you'll rarely type true or false yourself — they come from expressions:
fun main() {
val battery = 15
val charging = false
val low = battery < 20
println("Battery low: $low")
println("Needs warning: ${low && !charging}")
println("Full: ${battery == 100}")
}Battery low: true
Needs warning: true
Full: false
Combining conditions
| Expression | Result |
|---|---|
true && true |
true |
true && false |
false |
true || false |
true |
false || false |
false |
!true |
false |
Kotlin also offers the infix functions and, or and xor. Unlike && and || they always evaluate both sides (no short-circuit):
fun main() {
val a = true
val b = false
println(a and b)
println(a or b)
println(a xor b)
println(a xor true)
}false
true
true
false
Short-circuit evaluation
With &&, if the left side is false, the right side is never evaluated. This makes guard checks safe:
fun main() {
val name = ""
// name[0] would crash on an empty string, but it is never evaluated
val startsWithA = name.isNotEmpty() && name[0] == 'A'
println(startsWithA)
}false
Functions that return Boolean
Many standard functions answer questions: isEmpty(), contains(), startsWith(), isDigit(), any { … }. You can write your own too:
fun isLeapYear(year: Int): Boolean =
(year % 4 == 0 && year % 100 != 0) || year % 400 == 0
fun main() {
for (y in listOf(1900, 2000, 2024, 2025)) {
println("$y leap year? ${isLeapYear(y)}")
}
}1900 leap year? false
2000 leap year? true
2024 leap year? true
2025 leap year? false
Converting to and from text
true.toString() gives "true". Going the other way, "true".toBoolean() returns true (case-insensitive) and anything else returns false; toBooleanStrict() throws for anything other than exactly "true" or "false".
Note: Unlike C or JavaScript, Kotlin has no "truthy" values.
if (1)orif ("text")don't compile — a condition must be a realBoolean.
Test yourself
What is the value of 10 > 3 && 2 > 5?
- true
- false
- null
- Compile error
What is the difference between && and and?
- None
andalways evaluates both sides;&&short-circuitsandonly works on numbers&&is deprecated
Does if (1) { ... } compile in Kotlin?
- Yes, 1 is truthy
- No, the condition must be a Boolean
- Only with a warning
- Yes, but it is always false