Logical Operators Part 2
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 25 of 93.
The third logical operator is NOT (!). Unlike && and || which combine two conditions, the NOT operator works on a single Boolean value and flips it to its opposite.
If something is true, applying ! makes it false. If it's false, ! makes it true:
fun main() {
val isRaining = true
val isNotRaining = !isRaining
println(isNotRaining) // Prints: false
val isEmpty = false
println(!isEmpty) // Prints: true
}The NOT operator is particularly useful when you want to check for the opposite of a condition. For example, instead of checking if a user is logged in, you might need to check if they're not logged in:
fun main() {
val isLoggedIn = false
val needsLogin = !isLoggedIn
println(needsLogin) // Prints: true
}You can also apply ! directly to comparison expressions by wrapping them in parentheses:
fun main() {
val age = 15
val cannotVote = !(age >= 18)
println(cannotVote) // Prints: true
}Challenge
EasyWrite a function isUnavailable that takes isAvailable and returns the opposite value.
Use the NOT operator (!) to flip the boolean value.
Parameters:
isAvailable(Boolean): Whether something is currently available
Returns: true if not available, false if available (Boolean)
The supplied driver calls your function and prints its returned value. Keep the function signature and do not add a main function.
Try it yourself
fun isUnavailable(isAvailable: Boolean): Boolean {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground