Preferences datastore with dynamic name: Property delegate must have a 'getValue(Nothing?, KProperty*>) method

33 views Asked by At

Why does getting a datastore work when using val but not when using fun?

val Context.settingsDataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")

fun Context.test(name: String){
    // Property delegate must have a 'getValue(Nothing?, KProperty*>)' method. None of the following functions are suitable.
    val dataStore: DataStore<Preferences> by preferencesDataStore(name = name)
}

When clicking on the suggestion, the following code is generated:

private operator fun <T, V> ReadOnlyProperty<T, V>.getValue(v: V?, property: KProperty<V?>): V {

}

However, the operator has the following error: 'operator' modifier is inapplicable on this function: second parameter must be of type KProperty<*> or its supertype.


Originally, I thought the context was passed through this, but it turns out that there is no this when using val.

val Context.example = this.getString(R.string.example) // Extension property cannot be initialized because it has no backing field

// correct way
val Context.example: String
    get() = this.getString(R.string.example)
0

There are 0 answers