# Inline functions
- inline
- noinline
- crossinline
---
ubiquitous

---
Original source
{%youtube RM7aulixXC8 %}
---
## Inline functions
Using **higher-order functions** imposes certain runtime penalties: each function is an object, and it captures a closure.
```
public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> {
return filterTo(ArrayList<T>(), predicate)
}
```
----
### Higher-order functions
A higher-order function is a function that takes functions as parameters, or returns a function.
```
fun <T, R> Collection<T>.fold(
initial: R,
combine: (acc: R, nextElement: T) -> R
): R {
var accumulator: R = initial
for (element: T in this) {
accumulator = combine(accumulator, element)
}
return accumulator
}
```
---
### inline on normal function

---
### inline on higher-order function

---
### Called from a loop or in onDraw

---
### Reduce create object by inline

---
## noinline
If you don't want all of the lambdas passed to an inline function to be inlined, mark some of your function parameters with the **noinline** modifier
```
inline fun foo(inlined: () -> Unit, noinline notInlined: () -> Unit) { ... }
```
---
without noinline

---
with noinline

---
If need to return a lambda function...

---
If need to return a lambda function…

---
IDE will hint

---
## crossinline
To indicate that the lambda parameter of the inline function cannot use non-local returns, mark the lambda parameter with the **crossinline** modifier
```
inline fun f(crossinline body: () -> Unit) {
val f = object: Runnable {
override fun run() = body()
}
// ...
}
```
---
IDE will suggesst

---
crossinline will prohibit non-local returns

---
End

{"metaMigratedAt":"2023-06-17T15:30:13.497Z","metaMigratedFrom":"YAML","title":"Kotlin inline function","breaks":true,"description":"View the slide with \"Slide Mode\".","contributors":"[{\"id\":\"221b28c9-dedd-42a8-bd73-36286f5d1ebb\",\"add\":4887,\"del\":2559}]"}