When to use Property Delegation in Kotlin?

2019-08-09 23:25发布

问题:

I saw this great talk by Lisa Wray sometime back https://youtu.be/0cjr4K0tqs4?t=493 which inspired me to create different Property delegates for all my ViewBindings like BindActivity(layoutId), BindFragment, BindViewGroup, etc. My colleague had created extension functions for the same like Activity.bind(layoutId), View.bind(), ViewGroup.bind(), etc. which made me wonder which should be preferred over here. I tried decompiling the kotlin byte code and it :

  1. Property Delegation would create a new object like private final BindActivity binding$delegate = new BindActivity(2131361819);
  2. It seems to be using Reflection, something like the following to initialize KProperty :

    static final KProperty[] $$delegatedProperties = new KProperty[]{(KProperty)Reflection.property1(new PropertyReference1Impl(Reflection.getOrCreateKotlinClass(MainActivity.class), "binding", "getBinding()Lcom/abcd/package/databinding/ActivityMainBinding;")), … another lazy delegated property};

(ActivityMainBinding)this.binding$delegate.getValue((Activity)this, $$delegatedProperties[0])

Question 1: If property delegation uses reflection, what is the use-case to use them?

Questions 2: Also, kotlin’s Reflection class seems to be using some reflection factory kotlin.reflect.jvm.internal.ReflectionFactoryImpl so does it mean that the reflection could be not as slow in kotlin as in java?