12

Here's my code:

@Module
class SharedPrefs {
    @Module
    companion object {
        val KEY_COOKIE = "cookie"

        @JvmStatic
        @Provides
        fun putPref(key: String, value: String?) {
            val prefs = PreferenceManager.getDefaultSharedPreferences(App.context)
            val editor = prefs.edit()
            editor.putString(key, value)
            editor.commit()
        }

        @JvmStatic
        @Provides
        fun getPref(key: String): String? {
            val preferences = PreferenceManager.getDefaultSharedPreferences(App.context)
            return preferences.getString(key, null)
        }

        @JvmStatic
        @Provides
        var cookie : String?
            get() = getPref(KEY_COOKIE)
            set(value) {
                putPref(KEY_COOKIE, value)
            }

    }
}

The last @provides above var cookie generates a compile error of:

This annotation is not applicable to target member property without backing field or delegate

How do I correct this?

Johann
  • 27,536
  • 39
  • 165
  • 279

1 Answers1

29

Try using @get:Provides instead of just @Provides on the var cookie.

EDIT:

Btw, I think I know what you mean by Providing this var and I don't believe Dagger will let you do that. It will just read the value from the getter and be able to provide a Nullable String in the graph.

You need to wrap those two functions (setter and getter of the var cookie) in a wrapper object of some sort, and provide this wrapper in the Dagger instead of String?.

Bartek Lipinski
  • 30,698
  • 10
  • 94
  • 132
  • @العبد Dagger uses those `providing` functions only once (per scope) to build the dependency graph. If that function returns a constant instance (e.g. a `String`) it will not change throughout the lifecycle of that part of the dependency graph. If you return an object which can mutate (the wrapper I was referring to), the instance living in the dependency graph can return different values in its lifetime. – Bartek Lipinski Aug 02 '21 at 11:27
  • thk , my question what is mean by @get:Provides , this syntax is strange for me – العبد Aug 02 '21 at 13:08
  • @العبد why don't you read through [my other answer here at SO](https://stackoverflow.com/a/56985541/1993204) – Bartek Lipinski Aug 03 '21 at 09:46