fun main() {
val nums = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
// filter — keep elements matching a predicate
val evens = nums.filter { it % 2 == 0 }
println(evens) // [2, 4, 6, 8, 10]
// map — transform each element
val squares = nums.map { it * it }
println(squares) // [1, 4, 9, ..., 100]
// Chain — usually most readable
val sumOfEvenSquares = nums
.filter { it % 2 == 0 }
.map { it * it }
.sum()
println(sumOfEvenSquares) // 220
// reduce — collapse to a single value (no initial value)
val product = nums.reduce { acc, n -> acc * n }
println(product) // 3628800
// fold — like reduce but with an explicit initial value (handles empty lists)
val concat = nums.fold("") { acc, n -> "$acc-$n" }
println(concat) // -1-2-3-4-5-...-10
}
Create a free account and build your private vault. Share publicly whenever you want.