Delegated properties inside functions

Viewed 291

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

1 Answers

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.

Related