
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
When to Use an Inline Function in Kotlin
Kotlin is a statistically typed language. It has different options to handle higher-order functions. Kotlin came up with a wonderful solution for higher-order functions by introducing inline functions.
An Inline function is a kind of function that is declared with the keyword "inline" just before the function declaration. Once a function is declared inline, the compiler does not allocate any memory for this function, instead the compiler copies the piece of code virtually at the calling place at runtime.
You should opt for an inline function in Kotlin in the following situations −
When you need to access higher-order functions.
When you need to allocate memory more efficiently.
When you need to pass a functional type parameter.
You should not turn a huge function "inline" because it will downgrade the performance of the application.
Inline functions are useful when a function accepts another function or lambda as a parameter.
You can use an inline function when you need to prevent "object creation" and have better control flow.
Example
The following example demonstrates how to use an inline function in Kotlin.
fun main(args: Array<String>) { myInlineFun({ println("Call to inline function")}) } inline fun myInlineFun(myFun: () -> Unit ) { myFun() print("TutorialsPoint") }
Output
It will generate the following output
Call to inline function TutorialsPoint