We have a list of strings:

val strList = listOf("a"."ab"."abc"."abcd"."abcde"."abcdef"."abcdefg")
Copy the code

Then we want to filter out the list of string elements with odd lengths. We split the solution logic of this problem into two functions for combination implementation:

val f = fun(x: Int) = x % 2= =1 // Check whether the input Int is odd
val g = fun(s: String) = s.length // Returns the length of the input string argument
Copy the code

We then use the function h to encapsulate the logic of “the string length is odd”, and the code is as follows:

val h = fun(g: (String) - >Int, f: (Int) - >Boolean): (String) -> Boolean {
    return { f(g(it)) }
}
Copy the code

However, the h function declaration is a bit long, especially the arrow expression of the three function declaration types, which is not concise enough. Don’t worry, Kotlin has a simple Kotlin type alias. We use G, F, and H to declare three function types:

typealias G = (String) -> Int
typealias F = (Int) - >Boolean
typealias H = (String) -> Boolean
Copy the code

Then, our h function can be written as follows:

val h = fun(g: G, f: F): H {
    return { f(g(it)) } // It is important to note that {} cannot be omitted
}
Copy the code

In return {f(g(it))}, {} represents a Lambda expression and returns a (String) -> Boolean function type. If there is no {}, the return value is a Boolean type Boolean.

As you can see from the code example above, in Kotlin we can simply implement higher-order functions. Now that the logic has been implemented, run the test to see the result:

val strList = listOf("a"."ab"."abc"."abcd"."abcde"."abcdef"."abcdefg")
println(strList.filter { it.length % 2= =1 })
println(strList.filter(h(g, f)))
// [a, abc, abcde, abcdefg]
// [a, abc, abcde, abcdefg]
Copy the code

When you see the code for a composite function like h(g, f), you’re happy, you feel natural, it’s very close to the mathematical formula, it’s easy to understand.