August 2017
Intermediate to advanced
440 pages
10h
English
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! ...Read now
Unlock full access