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")}))
}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
}
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 usingnoinline
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 get() = x.fooValue == CONST_FOO set(x) {