Inline Functions in kotlin

yadunath narayanan
2 min readJan 12, 2021

I was hearing about inline keyword ,from the beginning of my kotlin learning.I was thinking what is this..? Java was straight forward,nothing like these keywords ,here inline ,crossline etc…Then one day I started reading about inline.Oh my god.. it's that easy..

So I will walkthrough an example of inline function

So let's take the below higher order function

fun findHotel(){
println("FindTheHotel")
bookRoom()
println("Completed")
}
fun bookRoom(){
println("Room Booked")
}

There is an option in android studio to convert this to java (Tools ->kotlin ->showKotlinbytecode).If you convert you will see below code

public void findHotel() {

System.out.println("FindTheHotel");
bookRoom();
System.out.println("Completed");
}
public void bookRoom() {
System.out.println("Room Booked");
}

so bookRoom() is created in java code also.We can avoid this and do the same operation from kotlin ,which will actually reduce the memory overhead of new function. That is inline functions .

Now we will see how it will differ if we are using inline keyword for bookRoom()

fun findHotel(){
println("FindTheHotel")
bookRoom()
println("Completed")
}

inline fun bookRoom(){
println("Room Booked")
}

Now if we convert the above code to java ,you will be able to see below code

public void findHotel() {

System.out.println("FindTheHotel");
System.out.println("Room Booked");
System.out.println("Completed");
}

That’s it..

inline is used normally for small functions .For large function inline is not recommended.

Inlining may cause the generated code to grow; however, if we do it in a reasonable way (i.e. avoiding inlining large functions), it will pay off in performance, especially at “megamorphic” call-sites inside loops.

for more deeper learning

Happy Reading … Happy Coding…

--

--

yadunath narayanan

Passionate android developer working with android mobile and androidTv