Skip to Content
Learn
Conditional Expressions
else-if Expressions

An else-if expression can be used to add a plethora of more conditionals for our program to evaluate.

Let’s say we created a Kotlin program that determines what we will wear depending on the temperature outside. If we just use an if/else expression, our options are limited:

var temp = 60 if (temp > 65) { println("Wear a t-shirt") } else { println("Wear a winter coat") } // Prints: Wear a winter coat

In real life, wearing a winter coat in 60-degree weather can cause a person to overheat. We need to wear something in between a heavy coat and a t-shirt, like a light jacket. We can place an else-if expression in our code to represent this “in-between” situation:

var temp = 60 if (temp > 65) { println("Wear a t-shirt") } else if (temp > 45) { println("Wear a light coat") } else { println("Wear a winter coat") } // Prints: Wear a light coat

Let’s examine this else-if statement:

  • The else-if expression must come after an if expression but before the else expression.
  • The else-if expression contains its own condition placed within parentheses: temp > 45.

The instruction println("Wear a light coat") is executed only if the condition in the if expression is false and the condition within the else-if expression is true. If both conditions are false, the instructions in the next conditional, the else expression, will execute.

An if-else expression can contain as many else-if expressions as needed. When using multiple else-if statements, the order in which they appear matters. The moment the program evaluates one of the conditionals as true, the program will execute that body of code and will not evaluate any of the conditionals that appear after.

Instructions

1.

The local coffee shop started a rewards program based on the amount of coffee a customer buys. Use your knowledge of conditionals to create a program that determines what kind of member a customer is based on the amount of rewards points they have.

If rewardsPoints is greater than or equal to 50:

  • Set the value of memberType to "Platinum".

Otherwise, if rewardsPoints is greater than or equal to 25:

  • Set the value of memberType to "Gold".

Otherwise, if rewardsPoints is greater than or equal to 10:

  • Set the value of memberType to "Silver".

Else:

  • Set the value of memberType to "Bronze".
2.

Outside of the conditional expressions, use println() and a String template to output the following:

You are a [memberType] type member.
Folder Icon

Take this course for free

Already have an account?