Kotlin map, foldRight & nested functions to implement redux middleware
Kotlin supports Higher order functions. In this blog, I will create a higher order function that will use map & fold right for execution.
Before diving into higher order functions, let’s go through map & fold right.
map is collective transform operation.
var numbers = mutableListOf(1, 2, 3)
numbers = numbers.map { it*2 }.toMutableList()
// elements in numbers: 2,4,6
foldRight accept initial state, apply initial state to all elements and return final state.
var numbers = mutableListOf(1, 2, 3)
var result = numbers.foldRight(100, {a,b -> test(a,b)})
private fun test(a: Int, b: Any): Int {
return a + b as Int
}
/*
First execution: initial 100
a = 3
b = 100
Second Execution
a = 2
b = 103
Third Execution
a = 1
b = 105
final: result = 106
*/
Let’s create a higher order function Middleware that takes an instance StringApp, has inner function next: Type and return Type.