๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

Kotlin Progressions

A progression is a run of values that moves from a first value to a last value by a fixed step. Numbers and characters both form progressions.

Walking a character range

A character range loops in letter order. Collecting the same range with toList() shows all of its letters at once.

fun main() {
    for (letter in 'a'..'e') {
        println(letter)
    }
    println(('a'..'e').toList())
}

Testing letters with in

The operator in checks a letter against the ends of the range. An uppercase letter and a digit both fall outside the lowercase range.

fun main() {
    println('x' in 'a'..'z')
    println('A' in 'a'..'z')
    println('5' in 'a'..'z')
}

Testing numbers with in and !in

Both ends of a numeric range count as inside it. The operator !in gives the opposite answer to in.

fun main() {
    println(7 in 1..10)
    println(12 in 1..10)
    println(12 !in 1..10)
    println(1 in 1..10)
}

Stepping and summing

A step of 2 lands only on the odd numbers in the range. The call sum() adds the collected values.

fun main() {
    val odds = (1..10 step 2).toList()
    println(odds)
    println(odds.sum())
    println((2..10 step 2).sum())
}

Counting down and reversing

The infix downTo walks toward the smaller end, and it accepts a step as well. The call reversed() flips a progression that was built upward.

fun main() {
    println((5 downTo 1).toList())
    println((10 downTo 1 step 3).toList())
    println((1..5).reversed().toList())
    println(('e' downTo 'a').toList())
}

Example

fun main() {
    val rows = ('a'..'d').toList()
    println(rows)
    println(rows.size)
    val seats = (1..20 step 4).toList()
    println(seats)
    println(seats.sum())
    println(9 in 1..20)
    println((20 downTo 1 step 4).toList())
}

Key points

  • Write a character range with two letters, such as the range from a to e, and loop over it letter by letter.
  • Use in to test whether a value sits inside a progression, and use !in to test that it sits outside.
  • A character test is exact, so an uppercase letter is not inside a lowercase range.
  • Use step to skip values, so the progression lands only on every second or third value.
  • Use downTo to build a progression that counts down instead of up.
  • Use toList() to collect a progression into a list, and use sum() to add its numbers.
  • Use reversed() to walk a progression in the opposite order.

In this example a hall plan is described with progressions. The rows come from a character range, the seat numbers come from a stepped range that sums to 45, one seat number is tested with in, and a downward stepped range lists the seats in reverse.

Note

A range printed on its own shows its start and end text, so the examples here always collect a progression before printing it.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

What does printing (1..12 step 3).toList() show?