I need a real life example when we can use this. I have gone through this link (https://kotlinlang.org/docs/reference/inline-functions.html) but not able to find a good example.
So let's say we have a higher-order function, which takes another function as a parameter
fun doSomething(block: () -> Unit){
}
the Kotlin compiler will convert this to equivalent Java code which would be,
void doSomething( new Function(){
void invoke(){
// the code which you passed in the functional parameter
}
})
The Kotlin compiler creates an Anonymous Inner Class for the functional parameter you passed and when you call this passed functional parameter the compiler internally calls this invoke()
method.
As a result, all functional parameter results in extra object creation and function call which is a performance and memory overhead.
We can avoid this overhead by introducing the inline
modifier. When added to a function the function call is skipped and the function code is added at the call site instead.
So let's say we have a simple testing function,
inline fun testing(block : () -> Unit){
println("Inside the testing block")
block()
someOtherRandomFunction()
}
and we call this testing function from the main function, like this
fun main(){
testing{
println("Passed from the main function")
}
}
When the above main function gets compiled, it would look like
fun main(){
println("Inside the testing block")
println("Passed from the main function")
someOtherRandomFunction()
}
As if no testing function ever existed, all the code body from the testing function is simply copy-pasted inside the main function body.
For example:
inline fun TextView.onTextChanged(crossinline onTextChangeListener: (String) -> Unit) {
addTextChangedListener(object: TextWatcher {
override fun afterTextChanged(editable: Editable) {
onTextChangeListener(editable.toString())
}
...
)
}
So if you're passing a lambda but you don't want to underneath create an anonymous inner class but rather inline the lambda into the call, then you can use inline
. If you need to invoke this lambda inside another anonymous object or lambda, you can use crossinline
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With