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:


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) { 
 // Prints: Hello! ...

Get Android Development with Kotlin now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.