Summary - Higher-order functions
- Kotlin course
- Intermediate
- Lesson 58/116
- 5 min
Combine lambdas, it and scope functions to write a processing pipeline.
Summary - Higher-order functions
In this group you learned function type, lambda, it, inline and scope functions. They all carry functions as values and enable short code.
In this summary you will write a pipeline: filter, transform and sum the numbers in a list. filter, map and sum are chained. When all parts come together you get a short, readable pipeline.
Practice The filter-map-sum pipeline
Declare val nums = listOf(1, 2, 3, 4, 5). Declare val result = nums.filter { it % 2 == 0 }.map { it * 10 }.sum(). In main call println(result).
Starter code
// the nums list
// a pipeline with filter, map and sum
// print the result in mainSample solution
val nums = listOf(1, 2, 3, 4, 5)
val result = nums.filter { it % 2 == 0 }.map { it * 10 }.sum()
fun main() {
println(result)
}Expected output
60
Practice Configuring a list with apply
Declare val list = mutableListOf<Int>().apply { add(10); add(20); add(30) }. In main call println(list).
Starter code
// list: add 10, 20, 30 with apply
// apply returns the object
// print the list in mainSample solution
val list = mutableListOf<Int>().apply { add(10); add(20); add(30) }
fun main() {
println(list)
}Expected output
[10, 20, 30]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why are <code>filter</code>, <code>map</code> and <code>sum</code> chained in a pipeline?
Each chain step returns a list; the next step takes it.- Because each requires a separate variable
- Because each step takes the previous result and produces a new one Correct answer
- Because they do not compile without chaining
- Because they only work with Int
Explanation: Each step returns a list; the next step takes it.
2 Complete the function type definition
val format: (Int) ____ String = { n -> "Number: $n" }
val format: (Int) -> String = { n -> "Number: $n" }
Explanation: -> marks the return type.