CodeBlanks Logo Icon CodeBlanks

Summary - Conditionals

Combine if, if expression and when to write a day-of-week app.

Summary - Conditionals

In this summary you'll combine if, the if expression and when to build a day-of-week app. In previous lessons you learned:

  • condition checks with if
  • alternative branches with else and else if
  • returning values with the if expression
  • multi-way selection with when

We'll do two mini tasks: convert a day number to a name (when expression) and categorize a temperature (if expression).

Practice Find the day name with when

Write a fun main(). Assign 3 to val day. Write val name = when (day) { 1 -> "Monday" 2 -> "Tuesday" 3 -> "Wednesday" 4 -> "Thursday" 5 -> "Friday" else -> "Weekend" }. Print the result with println(name).

Starter code

Main.kt
fun main() {
    // Find the day name
}

Sample solution

Main.kt
fun main() {
    val day = 3
    val name = when (day) {
        1 -> "Monday"
        2 -> "Tuesday"
        3 -> "Wednesday"
        4 -> "Thursday"
        5 -> "Friday"
        else -> "Weekend"
    }
    println(name)
}

Expected output

Wednesday

Practice Categorize the temperature

Write a fun main(). Assign 25 to val temp. Write val category = if (temp >= 30) "Hot" else if (temp >= 15) "Mild" else "Cold". Print the result with println(category).

Starter code

Main.kt
fun main() {
    // Categorize the temperature
}

Sample solution

Main.kt
fun main() {
    val temp = 25
    val category = if (temp >= 30) "Hot" else if (temp >= 15) "Mild" else "Cold"
    println(category)
}

Expected output

Mild

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is the most readable construct to compare a value against 5 options?

  • if/else if chain
  • Nested if
  • Ternary operator
  • when expression Correct answer

Explanation: when is the most readable for multi-way selection.

2 Complete the if expression

Question
val category = if (temp >= 30) "Hot" ____ "Normal"
Answer
val category = if (temp >= 30) "Hot" else "Normal"

Explanation: else gives the second branch's value in an if expression.

All lessons in Beginner