O'Reilly logo

Android Development with Kotlin by Igor Wojda, Marcin Moskala

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 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! ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required