kotlininline

Kotlin - When and when not to prefer inline function and why?


I have been using Kotlin for a while, I came across the fact that only a higher-order function can be an inline function, which is reasonable, But the question I want to ask is whether it is always necessary

  1. Should we make all the higher-order functions with one lambda parameter, an inline function?
  2. If we should or should not, and why we should and why we should not?
  3. I know one size does not fit all, so which scenario is fit for going inline and which is not?

Solution

  • Answering your questions:

    AD.1 As with everything in programming it depends. If it's a simple, short function, why not? If's a long complex function then I wouldn't do that. (Read the drawbacks) Also, JIT(Just-In-Time) performs inlining, you can read when it performs this optimization, and it should help you make the right decision.

    AD.2 If you're dealing with limited memory environments or situations where code size is a concern, I'd avoid inlining. Compilation time takes too long? Also, avoid this kind of optimization.

    AD.3

    It's all about the trade-offs, that you can accept. Generally, pros of inlining are:

    Inlining also has some drawbacks: