Search code examples
androidkotlinandroid-jetpack-composedelegated-properties

Kotlin Jetpack Compose Understanding Type in Delegate property


I'm having difficulty to understand Type of property when using delegated property. For example, from this Jetpack Compose documentation, it says both things are same.

 1. val name: String by helloViewModel.name.observeAsState("")
 2. val nameState: State<String> = helloViewModel.name.observeAsState("")

I've gone through the Kotlin Delegated property documentation here. For the first example, according to documentation, val name:String, when we try to read this name property, it will call getValue() function on the delegate instance, whose return type would be String, not State<String>. But how come it is returning State<String>, this part I didn't get completely.

Can you point me what I'm missing to understand this logic, or any link to documents/blog post would be great. Thanks


Solution

  • val nameState: State<String> = helloViewModel.name.observeAsState("")
    val name: String = nameState.value
    

    observeAsState's return type is State<R>, where R is String in this case (since name is declared as LiveData<String>). At this stage you can retrieve the state's value from State#value property.



    val name: String by helloViewModel.name.observeAsState("")
    

    This syntax is pretty similar, the only difference is it declares local variable as delegated property, where the delegate itself just returns the State's value property.

    The delegate's getValue implementation (from Compose's source code, note that it just returns the State's value):

    inline operator fun <T> State<T>.getValue(thisObj: Any?, property: KProperty<*>): T = value