Learning Kotlin: inline functions

Learning Kotlin: Inline functions

Kotlin is packed with amazing features that make us fall in love with the language. One of them is high order functions which lets you pass functions as parameters as well as return functions. But the fact that they are stored as objects may make the use disadvantageous at times because of the memory overhead. The thing is, each object is allocated space in memory heap and the methods that call this method are also allocated space. Check out a high order function in below snippet:

fun main(args: Array<String>) {
var a = 2
println(someMethod(a, {println("Just some dummy function")}))

A way to get around the memory overhead issue is, by declaring the function inline. inline annotation means that function as well as function parameters will be expanded at call site that means it helps reduce call overhead. The goal of this post is to get a basic understanding of inline in Kotlin so as to be able to identify how and when to use it in our code in future.

Declaring a function inline is simple, just add inline keyword to the function like in below code snippet :

inline fun someMethod(a: Int, func: () -> Unit):Int {
return 2*a

Basically inline tells the compiler to copy these functions and parameters to call site. Similarly, inline keyword can be used with properties and property accessors that do not have backing field.

A few more things to know when working with inline functions:

  • We can have some lambdas inlined, when passed in an inline function by using noinline modifier.
  • A normal return statement is not allowed inside a lambda. If we want to explicitly return from a lambda, we need to use a label
  • To access type passed as parameter we use reified type parameter.
  • As mentioned above we can inline properties in Kotlin, and also inline just specific accessor of a property. Check out the below code snippet to understand this better.
inline var x.fooProperty: Boolean

Or just declare a particular accessor of property as inline

var x.fooProperty: Boolean

So basically inline can be used when we wish to reduce memory overhead. But inline also increases the resulting bytecode. Which is why, inline usage should be avoided with large functions or accessors with large code logic.

I hope you now have a basic understanding of inline keyword in Kotlin. Now, it is time to get your hands dirty, try coding something using inline and don’t forget to respond with your first inline function.

And as always, follow me to read more on tech, design and spirituality. Wait, don’t forget to clap if you enjoyed this post.

Author of Kotlin Programming Cookbook | Android Developer | www.rashikaranpuria.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store