Inline function : Kotlin

What is inlining?

This post was originally posted at https://agrawalsuneet.github.io/blogs/inline-function-kotlin/ and reposted on Medium on 15th April 2019.

Why it is required?

Let’s take an example.

fun isMultipleOf (number: Int, multipleOf : Int): Boolean{
return number % multipleOf == 0
}
fun <T> ArrayList<T>.filterOnCondition(condition: (T) -> Boolean): ArrayList<T>{
val result = arrayListOf<T>()
for (item in this){
if (condition(item)){
result.add(item)
}
}
return result
}
var list = arrayListOf<Int>()
for (number in 1..10){
list.add(number)
}
val resultList = list.filterOnCondition { isMultipleOf(it, 5) }
print(resultList)
inline fun isMultipleOf (number: Int, multipleOf : Int): Boolean {
return number % multipleOf == 0
}

Things to keep in mind

  • We will lose access to any private variable or function of the class inside the inline function. So it’s better to make functions inline which are very generic and don’t use a class level variable or function to achieve their functionality.
private var localVariable : Int = 8inline fun isMultipleOf (number: Int, multipleOf : Int): Boolean {
print(localVariable) //compilation error
return number % multipleOf == 0
}
Public-API inline function cannot access non-public-API 'private var localVariable
  • Do not inline for bigger functions as it degrades the performance.

--

--

https://agrawalsuneet.github.io/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store