ProgramGuru

Smart casts and early validation

Smart casts and early validation

Once a function has established that a value is present, it should be able to use that knowledge safely. Kotlin smart casts narrow a value’s usable type after suitable checks when the compiler can prove the value has not changed. Early return keeps the successful path clear.

What you’ll learn

  • Validate presence and domain range separately.
  • Use a stable local value after a successful check.

Smart casts and early validation in the example

  1. Check presence

    Once a function has established that a value is present, it should be able to use that knowledge safely.

    Check presence
  2. Validate range

    An Elvis expression can return from a function when input is absent.

    Validate range
  3. Display valid mark

    The first call prints an absence message and returns.

    Display valid mark
The first call prints an absence message and returns. The second gets a non-null 80, validates its range and displays it. Presence and valid domain range are separate checks.

Understand smart casts and early validation

An Elvis expression can return from a function when input is absent. The resulting local value is non-null. Smart casts depend on stability: an open property or mutable field that could change cannot always be treated like an unchanged local val.

Follow smart casts and early validation

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

Kotlin/JVM · complete program

fun showScore(score: Int?) {
  val actual = score ?: return println("Awaiting result")
  if (actual !in 0..100) {
    println("Invalid score")
    return
  }
  println("Score: $actual")
}
fun main() {
  showScore(null)
  showScore(80)
}

Expected output

Awaiting result
Score: 80

Follow the execution

The first call prints an absence message and returns. The second gets a non-null 80, validates its range and displays it. Presence and valid domain range are separate checks.

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

Practice: Smart casts and early validation

Your task: What happens for showScore(120)?

Kotlin/JVM · complete program

fun showScore(score: Int?) {
  val actual = score ?: return println("Awaiting result")
  if (actual !in 0..100) {
    println("Invalid score")
    return
  }
  println("Score: $actual")
}
fun main() {
  showScore(null)
  showScore(80)
}

Worked answer

It prints Invalid score and returns before the score display. Being an Int is not enough to satisfy the school’s 0..100 policy.

Smart casts and early validation: the important boundary

Keep success-path assumptions near their checks. Do not bypass a failed smart cast by adding !! indiscriminately; use a stable local copy or redesign access when mutation makes a check unreliable.

Check your understanding

What happens for showScore(120)?
Choose one answer. You can try again.

Answer and explanation

It prints Invalid score and returns before the score display.

It prints Invalid score and returns before the score display. Being an Int is not enough to satisfy the school’s 0..100 policy.

Smart casts and early validation: what to keep in mind

It prints Invalid score and returns before the score display. Being an Int is not enough to satisfy the school’s 0..100 policy. Keep success-path assumptions near their checks.

Further reading: official Kotlin documentation for this topic.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: If and else as expressions →