Kotlin: Is local function passed to inline functions as inlined parameter?

When passing a lambda or anonymous function to inline functions as a parameter, it is quite simple, the code is inserted in the calling position, but when passing a local function as a parameter, the result seems different (as shown below). I wonder if it is embedded? Why or why not?

For example:

inline fun foo(arg: () -> Int): Int {
    return arg()
}

fun bar(): Int {
    return 0
}

fun main(args: Array<String>) {
    foo(::bar)
}

      

And the decompiled Java code:

public final class InlinedFuncKt {
   public static final int foo(@NotNull Function0 arg) {
      Intrinsics.checkParameterIsNotNull(arg, "arg");
      return ((Number)arg.invoke()).intValue();
   }

   public static final int bar() {
      return 0;
   }

   public static final void main(@NotNull String[] args) {
      Intrinsics.checkParameterIsNotNull(args, "args");
      bar();
   }
}

      

+3


source to share


2 answers


bar()

not declared inline. So why do you expect it to be inlined ?!

In other words: it would just be wrong that the signature of method A affects (implicitly) the signature of another method B.



Your idea (in some way) will affect the "semantics" of bar () - just because you used it bar()

as an argument for another method call.

+2


source


As you can in the decompiled code , kotlin does not build bar

in your case, but it does inline it if it is declared as inline fun bar()

.



The rule of thumb is that lambdas are inline when they are passed to an inline function. In all other cases, for example, when passing a reference to a function or a lambda object, inlining is not performed.

+2


source







All Articles