Updated 30 June 2022
In this blog, we going to discuss the Inline functions in Kotlin.
Functions are the basic building blocks for the program we use to define the set of functionality inside the function. Sometimes the few lines of functionality which is used in multiple places in our program will be used inside the separate function. Only function call is made for accessing the same.
In kotlin higher-order function and lambda expression, all are stored as an object. Memory allocation for all the functions and classes and for virtual calls might introduce the runtime overhead for the log file.
We simply inline the function and instruct the CPU not to allocate the memory for the function and just copy the body of the function on the calling place.
So by using this we reduce the memory overhead as well. If you want to learn the Inline functions then this blog is for you.
We will lose access to the private variables and functions of the class. So make the inline function only for the generic functionality which will not require access to the class variable.
Simply add the inline keyword before the function like below:
1 2 3 4 5 6 7 8 |
inline fun formatDate(dateFormat: String?, year: Int, month: Int, day: Int): String { val cal = Calendar.getInstance() cal.timeInMillis = 0 cal.set(year, month, day) val date = cal.time val sdf = SimpleDateFormat(dateFormat ?: "\"MM/dd/yy\"", Locale.getDefault()) return sdf.format(date) } |
On the above function we have created a generic function for formatting the date.
call the inline function same as a normal function.
1 |
val formatedDate = formatDate("MM/dd/yyyy", year, month, day) |
Kotlin compiler does not allow us to return from the lambda expression. With the help of the inline keyword, we can return from the lambda expression itself and exit the function in the inline function call.
In this blog, we have learned about the implementation of the Inline functions in Kotlin.
For more information regarding the Inline functions in Kotlin follow the link.
Thanks for reading this blog. You can also check other blogs from here.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.