Why the new property delegation syntax was introdu...
# language-evolution
a
Why the new property delegation syntax was introduced in Kotlin 1.4:
val delegatedProperty: Int by anotherObj::intProperty
using reflection? When
val delegatedProperty: Int get() = anotherObj.intProperty
works out of the box (getter property without field). Doesn't the former will have performance penalty due to reflections are involved (
KProperty0
as seen by decompiler).
g
KProperty doesn't mean that reflection are involved, yes it's part of reflection package, but it compile time intrinsic
👍 4
a
Here's a simple delegation code
Copy code
val a: Int = 5
val b: Int by ::a
Here's the decompiled code of it:
Copy code
final class TestKt$b$2 extends PropertyReference0Impl {
   public static final KProperty0 INSTANCE = new TestKt$b$2();

   TestKt$b$2() {
      super(TestKt.class, "a", "getA()I", 1);
   }

   @Nullable
   public Object get() {
      return TestKt.getA();
   }
}

public final class TestKt {
   private static final int a = 5;
   @NotNull
   private static final KProperty0 b$delegate;

   public static final int getA() {
      return a;
   }

   public static final int getB() {
      KProperty0 var0 = b$delegate;
      Object var1 = null;
      Object var2 = null;
      boolean var3 = false;
      return ((Number)var0.get()).intValue();
   }

   static {
      b$delegate = TestKt$b$2.INSTANCE;
   }
}
Generated by Intellij (with default settings)
Boxed type will have first penalty followed by extra step in instantiation, and string based reflective access of property.
g
Yep, you right, it would be boxed (as any code which involves lambda/reference) , but it doesn't involve runtime reflection
a
O really? Yes I understood it wrong, I thought another class is using reflection, but it was just calling getA() 😛
g
It works in a similar way as method reference
d
It looks like the generated code could still be improved by doing some inlining to eventually realize that
getB()
would be best off calling
getA()
directly, with no
KProperty
involved. In particular, I thought the 1.4 optimization was supposed to remove
KProperty
usage where it isn't needed, such as with
by lazy
.
☝️ 4