Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegated properties inside functions

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

like image 383
Marti Serra Molina Avatar asked Oct 15 '25 05:10

Marti Serra Molina


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.

like image 160
Commander Tvis Avatar answered Oct 18 '25 05:10

Commander Tvis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!