Can kotlin's function return a function object as a result?


#1

can kotlin’s function return a function object as a result?


#2

yes


#3

Yes, consider for example a function that takes a predicate and returns an inverted predicate:

fun <T> invert(predicate: (T) -> Boolean): (T) -> Boolean {
    return { !predicate(it) }
}

This function takes a functional type (T) -> Boolean as a parameter and returns it as a result.


#4

Also another useful feature of Kotlin regarding this are typealiases. For functions you pass around a lot you can create a type alias like this

typealias Predicate<T> = (T) -> Boolean

fun <T> invert (predicate: Predicate <T>): Predicate <T> {
    return { ! predicate(it) }
}

You can also name arguments of the typealias which can be helpful if your function takes multiple arguments

typealias Predicate<T> = (someArgName: T) -> Boolean