Logical Operators Part 3
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 26 of 93.
Precedence controls how an expression is grouped. ! binds most tightly, followed by &&, then ||. Thus a || b && c means a || (b && c).
val a = true
val b = false
val c = false
println(a || (b && c)) // true
println((a || b) && c) // falseGrouping is different from evaluation order. || stops when its left operand is true, and && stops when its left operand is false. In the first expression above, b && c is never evaluated because a is already true.
Parentheses can change grouping or make it explicit. Evaluate the left operand first, then determine whether the right operand is needed.
Challenge
EasyWrite a function canAccessFeature that takes isAdmin, isPremium, and hasTrialActive and returns whether a user can access a premium feature.
A user can access the feature if they are an admin, or if they are both a premium member and have an active trial.
Use parentheses to ensure the correct evaluation order: the && condition should be grouped together before being combined with ||.
Parameters:
isAdmin(Boolean): Whether the user is an administratorisPremium(Boolean): Whether the user has a premium subscriptionhasTrialActive(Boolean): Whether the user has an active trial period
Returns: true if the user can access the feature, 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 canAccessFeature(isAdmin: Boolean, isPremium: Boolean, hasTrialActive: 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