Search code examples
kotlininline

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


When passing a lambda or anonymous function to inlined functions as a parameter, it's quite simple, the code is pasted to the calling position, but when passing a local function as a parameter, the result seems different(shown as below). I wonder if it's inlined? 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 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();
   }
}

Solution

  • bar() is not declared to be inlined. So why would you expect it to be inlined?!

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

    Your idea would (somehow) affect "semantics" of bar() - just because you used bar() as argument to another method call.