Learning Kotlin: inline functions

Learning Kotlin: Inline functions

Rashi Karanpuria
AndroidPub
Published in
2 min readOct 11, 2017

--

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")}))
}
fun someMethod(a: Int, func: () -> Unit):Int {
func()
return 2*a
}

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 {
func()
return 2*a
}

--

--

Rashi Karanpuria
AndroidPub

Software Engineer @ Google | Author of Kotlin Programming Cookbook | www.rashikaranpuria.com