Menu
Coddy logo textTech

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 icon

Challenge

Easy

Write 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 age
  • hasMembership (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
}
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