- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- When to use inline function and when not to use it in C/C++?
- When should I use an Inline script and when to use external JavaScript file?
- What is an inline function in C language?
- How to use inline CSS style for an element in HTML?
- When to use an abstract class and when to use an interface in Java?
- Inline virtual function in C++
- When to Use an Alias vs Script vs a New Function in Bash
- How to use AutoCompleteTextView in an Android App using Kotlin?
- How to use inline CSS (Style Sheet) in HTML?
- When should I write the keyword 'inline' for a function/method in C++?
- How to use BroadcastReceiver in Kotlin?
- How to add an inline layer in HTML?
- How to use a custom font in an Android project using Kotlin?
- How to use SearchView in Android Kotlin?
- How to use CheckBox in Android Kotlin?
