KOTLIN / CHAPTER 02

Conditions, ranges, and iteration

Beginner

Use expression results and precise loop bounds.

By the end of this chapter

  • Use if and when as expressions
  • Distinguish inclusive and exclusive bounds
  • Accumulate a result safely

The idea

Kotlin can use if and when as expressions, so a selected branch can supply a value directly. An if expression used as a value requires both alternatives. A when expression compares cases in order and can make multi-case decisions readable. Keep cases specific enough to express the rule, and consider what should happen for inputs outside the familiar examples.

Ranges give loops explicit bounds. The range 1..4 includes both endpoints, while 0 until size excludes size and fits zero-based indexing. A step changes the spacing between visited values. Trace the actual visited sequence before reasoning about an accumulator, especially when a boundary is excluded or the range is empty.

Kotlin example
fun main() {
  var total = 0
  for (n in 1..5 step 2) total += n
  val label = if (total >= 8) "ready" else "practice"
  println("$total:$label")
}
Result
9:ready

The range visits one, three, and five. Their sum satisfies the condition, and the if expression supplies the ready label.

Try it yourself

Classify a score with when and test every boundary used by the branches.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What is printed?
var total = 0
for (i in 0 until 4) total += i
println(total)