typestar

Collection chains in Kotlin

filter, map and friends read left to right and never mutate.

fun main() {
    val legsKm = listOf(8.4, 11.2, 6.9, 14.5, 9.1)

    // Chains read left to right; each call returns a new list.
    val hardDays = legsKm.filter { it > 9.0 }
    println("$hardDays add up to ${hardDays.sum()} km")

    val paces = legsKm.map { km -> (60 * km / 4.5).toInt() }
    println("Minutes per leg: $paces")

    println("Total: ${legsKm.sumOf { it }} km in ${legsKm.count()} days")
    println("Any rest day? ${legsKm.any { it < 7.0 }}")
}

How it works

  1. filter { it > 9.0 } keeps the hard days; sum folds them.
  2. map transforms each leg into minutes with a named lambda parameter.
  3. sumOf, count and any answer the usual questions in one call each.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
432
Tokens
121
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 104 seconds.

Type this snippet

Step 2 of 3 in Collections, step 11 of 27 in Language basics.

← Previous Next →