Kotlin Booleans
Working with true/false values in Kotlin
✅ What are Kotlin Booleans?
Booleans represent true or false values in Kotlin. They're essential for decision-making, conditions, and controlling program flow through if statements, loops, and logical operations.
// Boolean variables
val isLoggedIn = true
val hasPermission = false
val isAdult = 25 >= 18 // true (comparison result)
val canAccess = isLoggedIn && hasPermission // false (logical operation)
Output:
isLoggedIn: true
hasPermission: false
isAdult: true
canAccess: false
Boolean Concepts
True/False
Only two possible values
val isReady = true
Comparisons
Results of comparing values
val isGreater = 10 > 5
Logical Operations
Combine multiple conditions
val both = true && false
Decision Making
Control program flow
if (isReady) { ... }
🔹 Creating Boolean Values
Different ways to create and assign boolean values:
// Direct assignment
val isActive = true
val isComplete = false
// From comparisons
val age = 20
val isAdult = age >= 18 // true
val isChild = age < 13 // false
val isTeenager = age >= 13 && age <= 19 // false
// From string comparisons
val username = "admin"
val password = "secret123"
val isValidUser = username == "admin" // true
val isValidPassword = password == "admin" // false
// From method calls
val text = "Hello World"
val isEmpty = text.isEmpty() // false
val hasContent = text.isNotEmpty() // true
val containsHello = text.contains("Hello") // true
// From null checks
val name: String? = "John"
val hasName = name != null // true
Output:
isAdult: true
isChild: false
isTeenager: false
isValidUser: true
containsHello: true
🔹 Logical Operators with Booleans
Combine and manipulate boolean values:
val hasAccount = true
val isVerified = false
val isPremium = true
val isBlocked = false
// AND operator (&&) - all conditions must be true
val canLogin = hasAccount && isVerified && !isBlocked // false
val canUpgrade = hasAccount && !isPremium // false
// OR operator (||) - at least one condition must be true
val canAccess = hasAccount || isVerified // true
val needsAction = !isVerified || isBlocked // true
// NOT operator (!) - reverses the boolean value
val isGuest = !hasAccount // false
val isBasicUser = !isPremium // false
val isActive = !isBlocked // true
// Complex combinations
val fullAccess = hasAccount && isVerified && isPremium && !isBlocked // false
val limitedAccess = hasAccount && !isBlocked // true
val requiresVerification = hasAccount && !isVerified // true
Output:
canLogin: false
canAccess: true
isActive: true
fullAccess: false
limitedAccess: true
🔹 Booleans in Conditional Statements
Use booleans to control program flow:
val score = 85
val isLoggedIn = true
val hasPermission = false
// Simple if statements
if (isLoggedIn) {
println("Welcome back!")
} else {
println("Please log in")
}
// Multiple conditions
if (isLoggedIn && hasPermission) {
println("Access granted")
} else if (isLoggedIn && !hasPermission) {
println("Access denied - insufficient permissions")
} else {
println("Please log in first")
}
// Boolean expressions in when
val status = when {
score >= 90 -> "Excellent"
score >= 80 -> "Good"
score >= 70 -> "Average"
else -> "Needs improvement"
}
// Ternary-like expressions
val message = if (isLoggedIn) "Dashboard" else "Login Page"
val accessLevel = if (hasPermission) "Full" else "Limited"
Output:
Welcome back!
Access denied - insufficient permissions
status: Good
message: Dashboard
🔹 Boolean Functions and Methods
Useful functions that work with or return booleans:
// String boolean methods
val text = "Kotlin Programming"
val isEmpty = text.isEmpty() // false
val isNotEmpty = text.isNotEmpty() // true
val isBlank = " ".isBlank() // true
val isNotBlank = text.isNotBlank() // true
// Collection boolean methods
val numbers = listOf(1, 2, 3, 4, 5)
val emptyList = emptyList()
val hasElements = numbers.isNotEmpty() // true
val noElements = emptyList.isEmpty() // true
val hasEvenNumbers = numbers.any { it % 2 == 0 } // true
val allPositive = numbers.all { it > 0 } // true
// Range checks
val age = 25
val isInRange = age in 18..65 // true
val isNotInRange = age !in 1..17 // true
// Custom boolean functions
fun isValidEmail(email: String): Boolean {
return email.contains("@") && email.contains(".")
}
fun isWeekend(dayOfWeek: Int): Boolean {
return dayOfWeek == 6 || dayOfWeek == 7 // Saturday or Sunday
}
val email = "[email protected]"
val validEmail = isValidEmail(email) // true
val weekend = isWeekend(6) // true
Output:
isEmpty: false
hasElements: true
hasEvenNumbers: true
isInRange: true
validEmail: true
🔹 Boolean Best Practices
Tips for working effectively with booleans:
Naming Conventions:
- Use descriptive names: isLoggedIn, hasPermission, canEdit
- Start with is/has/can: isActive, hasData, canAccess
- Avoid negatives: isNotEmpty vs isEmpty
- Be specific: isEmailValid vs isValid
// Good boolean naming
val isUserLoggedIn = true
val hasValidLicense = false
val canEditProfile = true
val isEmailVerified = false
// Avoid double negatives
val isEnabled = true // Good
val isNotDisabled = true // Confusing
// Use meaningful names
val flag = true // Bad - unclear purpose
val isDataLoaded = true // Good - clear purpose
// Group related booleans
data class UserPermissions(
val canRead: Boolean,
val canWrite: Boolean,
val canDelete: Boolean,
val isAdmin: Boolean
)
val permissions = UserPermissions(
canRead = true,
canWrite = false,
canDelete = false,
isAdmin = false
)