From my understanding:Invoking a function means executing the function and getting its return value.
Referencing a function means treating the function as a value without executing it, e.g., passing it as an argument to another function without the parentheses.
Could someone provide more in-depth information or examples on:
The practical scenarios where referencing a function is essential(in real world app if possible)
How callbacks and higher-order functions utilize function references.
Any potential pitfalls or common mistakes when handling function references and invocations.
fun greet(name: String) = "Hello $name!"
// simplified version of the real map implementation
public inline fun <T, R> List<T>.map(transform: (T) -> R): List<R> {
var result = mutableList<R>()
for(t in this) {
result += transform(t) // short for: transform.invoke(t)
}
return result
}
fun main() {
val greetings = listOf("Peter", "Paul", "Mary").map(::greet)
}
map
expects a function (T) -> R
, and in our case T
is String
, so the greet
function fits the bill. Note that we don’t use curly braces after map, as we don’t want to define a lambda as usual, but just pass a function as a normal argument. When map
wants to use the function passed as “transform
”, it just calls it with an argument (directly or via invoke
, doesn’t make a difference)
3 Likes