ProgramGuru

If and else as expressions

If and else as expressions

A school uses a stated pass mark to choose a message. An if statement evaluates a Boolean condition and runs its branch when true. An else branch handles the alternative, so the program can give one appropriate message rather than always printing both.

Kotlin if can produce a value, so you can assign the selected branch’s result. A condition must be Boolean. When using if as a value-producing expression, provide the alternative needed to supply a result on every path. Braces group statements, and the branch’s final expression can supply its value.

What you’ll learn

  • Use if to select a value.
  • Test an inclusive pass boundary.

If and else as expressions in the example

  1. Read score

    A school uses a stated pass mark to choose a message.

    Read score
  2. Evaluate >= 75

    Kotlin if can produce a value, so you can assign the selected branch’s result.

    Evaluate >= 75
  3. Run one branch

    The condition includes 75, so the Pass string becomes message.

    Run one branch
The condition includes 75, so the Pass string becomes message. The other string is not selected. Printing happens afterward and is independent of the branch selection.

Follow if and else as expressions

Save the complete source as Main.kt and use the Kotlin/JVM environment. No separate input file is needed.

Kotlin/JVM · complete program

fun main() {
  val score = 75
  val message = if (score >= 75) "Pass" else "More practice"
  println(message)
}

Expected output

Pass

Follow the execution

The condition includes 75, so the Pass string becomes message. The other string is not selected. Printing happens afterward and is independent of the branch selection.

Try this in the Kotlin compiler by pasting the complete program.

Practice: If and else as expressions

Your task: What message results at score 74?

Kotlin/JVM · complete program

fun main() {
  val score = 75
  val message = if (score >= 75) "Pass" else "More practice"
  println(message)
}

Worked answer

More practice is selected because 74 is below the inclusive threshold.

If and else as expressions: the important boundary

Check higher thresholds first in overlapping grade bands. A well-typed expression can still implement the wrong school policy; test the boundary values.

Check your understanding

What message results at score 74?
Choose one answer. You can try again.

Answer and explanation

More practice is selected because 74 is below the inclusive threshold..

More practice is selected because 74 is below the inclusive threshold.

If and else as expressions: what to keep in mind

More practice is selected because 74 is below the inclusive threshold. Check higher thresholds first in overlapping grade bands.

Further reading: official Kotlin documentation for this topic.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: When expressions and matching →