Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the correct use of inline function in kotlin? [duplicate]

Tags:

android

kotlin

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.

like image 703
rahul khurana Avatar asked Dec 31 '19 11:12

rahul khurana


2 Answers

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.

like image 130
iCantC Avatar answered Oct 25 '22 19:10

iCantC


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.

like image 39
EpicPandaForce Avatar answered Oct 25 '22 19:10

EpicPandaForce