How to read this? val filter = {predicate: (...
# getting-started
s
How to read this? val filter = {predicate: (Int) -> Boolean -> {collection: List<Int> -> collection.filter(predicate) }}
The part i get is predicate being a function type with one Int parameter and returning boolean
d
It defines a lambda function that takes another lambda (
predicate
). It then returns a third lambda, which will take a collection as it's parameter and then return that collection filtered by the
predicate
.
Replacing the top level lambda with a function makes it more readable:
Copy code
fun createFilterFunction(predicate: (Int) -> Boolean): (List<Int>) -> List<Int> {
    return { collection: List<Int> ->
        collection.filter(predicate)
    } 
}
👍 1
r
@Sam Please enclose code blocks with three backticks ``` to give the code proper formatting and a monospace font.
s
@diesieben07 Thanks, that helps. @robin sure
Copy code
val testNestedLambda = { input : () -> () -> Unit -> {
        println("executing returned lambda")
        input()() } 
    }
    
    val returnedLambda = testNestedLambda{ { println( "passed lambda") } }
    
    returnedLambda()
Higher order functions, nostalgic functions pointers from C :-)
I guess, the key is to read from left to right
Copy code
val filter : ( (Int) -> Boolean ) -> ( List<Int> ) -> List<Int> = { predicate -> { collection ->
             collection.filter( predicate )        
       } 
    }
Moving type declaration to the variable also helps in reading it