Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 532
Johann Avatar asked May 20 '19 16:05

Johann


1 Answers

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?.

like image 122
Bartek Lipinski Avatar answered Nov 09 '22 19:11

Bartek Lipinski