pRaNaY
pRaNaY

Reputation: 25312

Only specific lambdas or arguments should be inline while creating inline function in kotlin

While using inline functions, kotlin will inlined all things. Like function and arguments or lambdas which passed in function. Example:

inline fun <T> myFun(getUserName: () -> String, getUserMobile: () -> String): T {
    // ...
}

Here in above example, getUserName() and getUserMobile() both will be inlined because we declare myFun as inline function.

As per kotlin doc:

The inline modifier affects both the function itself and the lambdas passed to it: all of those will be inlined into the call site.

Question is:

Can we declare the function which has inline and non-inline arguments?

Upvotes: 0

Views: 61

Answers (1)

pRaNaY
pRaNaY

Reputation: 25312

Sometimes we need some lambdas or arguments to be inlined and no need to other lambdas or arguments work as inline.

To avoid them as inlined we can use noinline modifier.

Example:

inline fun <T> myFun(getUserName: () -> String, noinline getUserMobile: () -> String): T {
    // ...
}

As per Kotlin doc:

Inlinable lambdas can only be called inside the inline functions or passed as inlinable arguments, but noinline ones can be manipulated in any way we like: stored in fields, passed around etc.

Check out more about Inline Functions: https://kotlinlang.org/docs/reference/inline-functions.html#inline-functions

Upvotes: 1

Related Questions