Function references

Sometimes, functions that we want to pass as an argument are already defined as a separate function. Then we can just define the lambda with its call:

    fun isOdd(i: Int) = i % 2 == 1 
 
    list.filter { isOdd(it) } 

But Kotlin also allows us to pass a function as a value. To be able to use a top-level function as a value, we need to use a function reference, which is used as a double colon and the function name (::functionName). Here is an example of how it can be used to provide a predicate to filter:

    list.filter(::isOdd) 

Here is an example:

    fun greet(){ 
        print("Hello! ") 
    } 
 
    fun salute(){ 
        print("Have a nice day ") 
    } 
 
    val todoList: List<() -> Unit> = listOf(::greet, ::salute) 
 
    for (task in todoList) { 
        task()  
    } 
 // Prints: Hello! ...

Get Android Development with Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.