3

I don't really understand why we can use delegated properties inside functions. We cannot create properties inside functions because inside functions we can only create variables.

How come is possible creating a delegated property inside a function then?

This line of code is a delegated property inside a function and I don't understand why is that possible.

val scoreFragmentArgs by navArgs<ScoreFragmentArgs>()

It has getters and setters and it doesn't make sense to me

  • Is that creating a property, or just a variable? – gidds Jul 13 '20 at 16:18
  • As for why, properties instead of variables inside of functions would be very heavy on GC churn because it would mean creating functional objects every time you use what would normally be a simple variable in Java. With a delegate, you are explicitly declaring you want a defined getter and setter and you are actively choosing to create the overhead of the object that handles it. – Tenfour04 Jul 13 '20 at 17:24

1 Answers1

2

Kotlin Delegates are based on storing the delegate object, and delegating getting/setting of the changes to it. So, it is possible to inline getValue calls when accessing to delegated variable.

For example:

import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty

object Delegate : ReadOnlyProperty<Any?, Int> {
    override fun getValue(thisRef: Any?, property: KProperty<*>): Int = 42
}

fun main() {
    val foo by Delegate
    println(foo)
}

The main method in Java will look like:

   static final KProperty[] $$delegatedProperties = new KProperty[]{(KProperty)Reflection.property0(new PropertyReference0Impl(Reflection.getOrCreateKotlinPackage(MainKt.class, "123"), "foo", "<v#0>"))};

   public static void main() {
      System.out.println(Delegate.INSTANCE.getValue(null, $$delegatedProperties[0]));
   }

As you see, accessing the variable is replaced by calling getValue.

Commander Tvis
  • 2,244
  • 2
  • 15
  • 41