# Inline functions - inline - noinline - crossinline --- ubiquitous ![](https://i.imgur.com/NvWvORL.png) --- 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 ![](https://i.imgur.com/WgTyDFz.png) --- ### inline on higher-order function ![](https://i.imgur.com/ay9XaUl.png) --- ### Called from a loop or in onDraw ![](https://i.imgur.com/B3Waa6w.png) --- ### Reduce create object by inline ![](https://i.imgur.com/Mqp9YGZ.png) --- ## 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 ![](https://i.imgur.com/NWs476u.png) --- with noinline ![](https://i.imgur.com/p5SY0QG.png) --- If need to return a lambda function... ![](https://i.imgur.com/ISsUMdP.png) --- If need to return a lambda function… ![](https://i.imgur.com/m1drvXU.png) --- IDE will hint ![](https://i.imgur.com/ZhRiVUk.png) --- ## 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 ![](https://i.imgur.com/Yr5dvew.png) --- crossinline will prohibit non-local returns ![](https://i.imgur.com/x8awiL7.png) --- End ![](https://i.imgur.com/CoIUfCQ.png)
{"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}]"}
    302 views