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
filter { it > 9.0 }keeps the hard days;sumfolds them.maptransforms each leg into minutes with a named lambda parameter.sumOf,countandanyanswer the usual questions in one call each.
Keywords and builtins used here
funitmainval
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.
Step 2 of 3 in Collections, step 11 of 27 in Language basics.