Built-in
higher-order functions
Kotlin Study Group #3
Andy Lu
2021.06.17
Who am I
Andy Lu
Android Engineer in FutureDial
第二屆 Kotlin 讀書會導讀者
❤ Kotlin
❤ Flutter
Medium: https://medium.com/@andyludeveloper
2
Agenda
● Recap higher-order fuction
● Built-in higher-order functions
● Functional programming
● Q&A
3
Recap higher-order function
4
What’s higher-order function?
5
What’s higher-order function?
6
Function as
arguments
(one or more)
What’s higher-order function?
7
Function as
arguments
(one or more)
Returns
function as a
results.
Why higher-order function?
8
Why higher-order function?
9
No temporary variables
Why higher-order function?
10
No temporary variables
Function call chaining
Why higher-order function?
11
No temporary variables
Function call chaining
Higher level of abstraction
How to use higher-order function?
Ex: { a, b -> a+b }
● { }
● Parameters (a, b)
● Body (after ->)
12
Built-in higher-order functions
13
minBy, maxBy
14
minByOrNull
15
maxByOrNull
16
Thinking
How to find the oldest child?
17
Use maxByOrNull
18
sumBy, sumByDouble
19
sumBy
20
sumByDouble
21
Thinking
22
How to calculate all the donate?
Use sumBy
23
Use for-loop
24
Temporary variable
filter
25
filter
26
Predicate
Filtered list
● Filtered new list
filter
27
[“three”, “four”]
Family of filter
● filter
● filterTo
● filterNot
● filterIndexed
● ...
28
map
29
map
30
● Collection transformation.
● Build new collection
For each subsequent element
map
31
[6, 12, 18, 24]
Family of map
● map
● mapNotNull
● mapKeys
● mapValues
● mapIndexed
32
forEach
33
forEach
34
● for-loop like
● Support function call chaining
● No return value
forEach - V.S for-loop
35
Function call chaining
36
Function call chaining
37
Closure
38
groupBy
39
groupBy
40
● Grouping collection elements
groupBy
{3=[one, two], 5=[three], 4=[four]}
41
fold
42
fold
43
● Operator and accmulate result
fold
20
44
Functional Programming
45
Three types of functions
46
Transform
map zip
flatten ...
Filter
filter
partition
...
Combine
fold
reduce
max
sum
...
Q & A
47

[2021] kotlin built-in higher-order functions