what's the difference between The Method reference and lambda expression in kotlin?

Viewed 33

I'm testing the difference between method ref and lambda. I tried using both, and found the difference in decompiled code.

that was like below.

public final class TestKt {
   public static final void main() {
      final Print printTest = new Print();
      text((Function0)(new Function0() {
         // $FF: synthetic method
         // $FF: bridge method
         public Object invoke() {
            this.invoke();
            return Unit.INSTANCE;
         }

         public final void invoke() {
            printTest.print();
         }
      }));
   }

   // $FF: synthetic method
   public static void main(String[] var0) {
      main();
   }

   public static final void text(@NotNull Function0 textClick) {
      Intrinsics.checkNotNullParameter(textClick, "textClick");
      textClick.invoke();
   }
}

and Method Ref was like below

public final class TestKt {
   public static final void main() {
      Print printTest = new Print();
      text((Function0)(new Function0(printTest) {
         // $FF: synthetic method
         // $FF: bridge method
         public Object invoke() {
            this.invoke();
            return Unit.INSTANCE;
         }

         public final void invoke() {
            ((Print)this.receiver).print();
         }
      }));
   }

   // $FF: synthetic method
   public static void main(String[] var0) {
      main();
   }

   public static final void text(@NotNull Function0 textClick) {
      Intrinsics.checkNotNullParameter(textClick, "textClick");
      textClick.invoke();
   }
}

The only difference is this code

text((Function0)(new Function0() //Lambda

text((Function0)(new Function0(printTest) // Method Ref

But I don't understand exactly the difference. And when I deep dive into Function0, that was an interface and no constructor for printTest.

Studying jetpack compose, I realized that I have to use the method reference because lambda hashcode changed when recomposition. But testing this codes, I'm not sure about what I know.

0 Answers
Related