How to Work with Inline Properties in Kotlin?
In this article, we are going to discuss how to work with inline properties in Kotlin. but before that, you should know some basics of functions and should be familiar with OOPs concepts. A great thing about Kotlin is high-order functions that let us use functions as parameters to other functions. However, they are objects, so they present memory overhead (because every instance is allocated space in heap, and we need methods for calling the functions too). We can improve the situation using inline functions. Inline annotation means that the specific function, along with the function parameters, will be expanded at the call site; this helps reduce call overhead. Similarly, the inline keyword can be used with properties and property accessors that do not have the backing field.
Let’s see how to work with inline properties in these steps:
1. Let’s try an example where we inline an accessor of property in Kotlin:
2. In this example, we just used the inline keyword with the get accessor. We can also declare both the get and set accessors as inline by making the whole property inline, as shown in this code snippet:
In the preceding snippet, both accessors are inlined.
3. One thing to keep in mind, though, is that inline does not work with property or accessor if the property has a backing field or the assessor does not reference the backing field. The code here is an example of a scenario where we cannot use inline:
another thing to keep in mind is that, although inline properties reduce call overhead by getting expanded only at the call site, they also increase the overall bytecode, so inline should not be used with large functions or accessors.
So, basically, we use inline when we wish to reduce memory overhead. Like the inline function, we can also declare properties as inline or the accessors of properties as inline. However, one thing to keep in mind is that inlining increases bytecode considerably, so it is suggested to not inline functions or accessors that have a large code logic.
Please Login to comment...