Menu
Coddy logo textTech

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) // false

Grouping 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 icon

Challenge

Easy

Write 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 administrator
  • isPremium (Boolean): Whether the user has a premium subscription
  • hasTrialActive (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
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground