Lesson 12 of 17
List Operations
Transforming Lists
Kotlin lists have powerful higher-order methods:
map — transform each element
val nums = listOf(1, 2, 3, 4, 5)
val doubled = nums.map { it * 2 } // [2, 4, 6, 8, 10]
filter — keep elements that match
val evens = nums.filter { it % 2 == 0 } // [2, 4]
fold — accumulate into a single value
val sum = nums.fold(0) { acc, x -> acc + x } // 15
any / all
nums.any { it > 4 } // true
nums.all { it > 0 } // true
Your Turn
Given the list [1, 2, 3, 4, 5, 6], print the list of squares, then the list of odd numbers, then the sum of all elements.
JS Transpiler loading...
Loading...
Click "Run" to execute your code.