Menu
Coddy logo textTech

Ternary With If Expression

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 27 of 93.

Many programming languages have a ternary operator: a shorthand way to choose between two values based on a condition. In Kotlin, there's no separate ternary operator because if itself can be used as an expression that returns a value.

Instead of writing condition ? valueIfTrue : valueIfFalse like in other languages, Kotlin uses if directly:

fun main() {
    val age = 20
    val status = if (age >= 18) "Adult" else "Minor"
    println(status)  // Prints: Adult
}

The if expression evaluates the condition and returns one of two values. If the condition is true, it returns the value after if. If false, it returns the value after else.

This result can be stored in a variable or used directly.

fun main() {
    val score = 85
    println(if (score >= 60) "Pass" else "Fail")  // Prints: Pass
}

This compact syntax is perfect for simple either-or decisions where you need to assign or return a value based on a single condition.

challenge icon

Challenge

Easy

You are provided with the following variables:

val temperature = 28
val isSunny = true

Create a variable activity that uses an if expression to choose between two activities based on the weather conditions.

Logic:

  • If the temperature is greater than 25 and it is sunny, assign "Go to the beach"
  • Otherwise, assign "Stay indoors"

Use the compact if expression syntax (single line) to assign the value directly to activity.

Print the value of activity.

Try it yourself

fun main() {
    val temperature = 28
    val isSunny = true
    
    // TODO: Write your code below
    // Create a variable 'activity' using an if expression (single line)
    // If temperature > 25 AND isSunny, assign "Go to the beach"
    // Otherwise, assign "Stay indoors"
    
    
    // Print the activity
    // println(activity)
}
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