Menu
Coddy logo textTech

If As An Expression

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

You've seen how if can be used inline to choose between two values. But when your if-else blocks contain multiple statements, you can still use the entire structure as an expression: the last expression in each branch becomes the returned value.

fun main() {
    val score = 85
    
    val message = if (score >= 60) {
        val grade = "passing"
        "You got a $grade score!"
    } else {
        val grade = "failing"
        "You got a $grade score."
    }
    
    println(message)  // Prints: You got a passing score!
}

Each branch can contain multiple statements, but the last expression in the branch is what gets returned and assigned to the variable. In this case, the string on the final line of each block becomes the value of message.

This also works with else if chains:

fun main() {
    val temperature = 25
    
    val description = if (temperature > 30) {
        "Hot"
    } else if (temperature > 20) {
        "Warm"
    } else {
        "Cool"
    }
    
    println(description)  // Prints: Warm
}

When using if as an expression, the else branch is required: Kotlin needs to guarantee a value is returned regardless of which condition is true.

challenge icon

Challenge

Easy

You are provided with the following variable:

val hours = 45

Use an if expression with multiple statements in each branch to determine a worker's pay status and create a message.

Create a variable payStatus using an if expression:

  • If hours is greater than 40:
    • Create a variable overtime equal to hours - 40
    • The last expression should be "Overtime: $overtime extra hours"
  • Otherwise:
    • Create a variable remaining equal to 40 - hours
    • The last expression should be "Regular: $remaining hours until overtime"

Print the value of payStatus.

Try it yourself

fun main() {
    val hours = 45
    
    // TODO: Write your code below
    // Create a variable payStatus using an if expression
    // If hours > 40: create overtime variable and return "Overtime: $overtime extra hours"
    // Otherwise: create remaining variable and return "Regular: $remaining hours until overtime"
    
    
}
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