Kotlin Inline

Usage

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.

1
2
3
4
5
6
7
8
9
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.

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

Example