Junior — Middle
What is the difference between passing a variable of type int and passing a function via lambda in an inline function?
sobes.tech AI
Answer from AI
In Kotlin, declaring an inline function involves different mechanisms for passing an int variable and passing a function via lambda:
- Passing an int is passing by value (copying), which is fast and simple.
- Passing a lambda usually creates a function object and a closure, which can affect performance.
However, if the function is declared as inline, the compiler inserts the lambda body directly at the call site, eliminating the overhead of creating an object and calling the function. This improves performance when using lambdas.
Example:
inline fun doSomething(x: Int, action: () -> Unit) {
println("Value: $x")
action() // lambda will be inlined here
}
fun main() {
doSomething(5) {
println("Action executed")
}
}
Here, the lambda does not create an additional object thanks to inline, and the int is passed as a regular parameter.