call
- Kotlin course
- Advanced
- Lesson 64/83
- 5 min
Learn dynamic calls with KFunction.call.
Calling functions with call
You can call a function at runtime with KFunction.call(args...) or invoke(args...). Arguments are passed in order.
Example: fun double(n: Int): Int = n * 2. val fn = ::double. fn.call(5) returns 10. fn.invoke(7) gives the same result. This pattern calls function references dynamically.
invoke vs call
invoke and call are functionally the same; both call the KFunction. invoke is declared as an operator function; it can be called as fn(args).
Example: val fn = ::double. fn.invoke(5) and fn(5) give the same result. call is more explicit; invoke gives a shorter syntax. Both do runtime type checks; wrong argument count throws.
Practice Call double with call
Define fun double(n: Int): Int that returns n * 2. In main take the reference val fn = ::double and print fn.call(5) and fn.invoke(7) on separate lines with println.
Starter code
// double function: returns n * 2
// in main take fn reference, print call and invoke resultsSample solution
fun double(n: Int): Int {
return n * 2
}
fun main() {
val fn = ::double
println(fn.call(5))
println(fn.invoke(7))
}Expected output
10 14
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method calls a KFunction at runtime?
- apply()
- let()
- call() Correct answer
- also()
Explanation: call() invokes a KFunction.
2 Match the call parts
| Term | Meaning |
|---|---|
::double |
Function reference |
fn.call(5) |
Call |
fn.invoke(7) |
Operator call |
10 |
Result |
3 Complete the call
val fn = ::double
val r = fn.____(5)
val fn = ::double
val r = fn.call(5)
Explanation: fn.call(5) invokes the function.