CodeBlanks Logo Icon CodeBlanks

Summary - Higher-order functions

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

Main.kt
// the nums list
// a pipeline with filter, map and sum
// print the result in main

Sample solution

Main.kt
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

Main.kt
// list: add 10, 20, 30 with apply
// apply returns the object
// print the list in main

Sample solution

Main.kt
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?

Main.kt
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

Question
val format: (Int) ____ String = { n -> "Number: $n" }
Answer
val format: (Int) -> String = { n -> "Number: $n" }

Explanation: -> marks the return type.

All lessons in Intermediate