Logical Operators Part 1
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 24 of 93.
Now that you can compare values, let's learn how to combine multiple conditions. Logical operators allow you to build more complex expressions by connecting Boolean values together.
The AND operator (&&) returns true only when both conditions are true. If either condition is false, the entire expression is false:
fun main() {
val age = 25
val hasLicense = true
val canDrive = age >= 18 && hasLicense
println(canDrive) // Prints: true
}Both conditions must be met: the person must be at least 18 and have a license. If the age were 16, canDrive would be false even though hasLicense is true.
The OR operator (||) returns true when at least one condition is true. It only returns false when both conditions are false:
fun main() {
val isWeekend = false
val isHoliday = true
val canSleepIn = isWeekend || isHoliday
println(canSleepIn) // Prints: true
}Here, you can sleep in if it's a weekend or a holiday: only one needs to be true.
Challenge
EasyWrite a function canEnterClub that takes age and hasMembership and returns whether a person can enter a club.
A person can enter the club only if they are at least 21 years old and have a membership.
Parameters:
age(Int): The person's agehasMembership(Boolean): Whether the person has a club membership
Returns: true if the person meets both requirements, false otherwise (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 canEnterClub(age: Int, hasMembership: 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