Override getter/setter for a type?

Preface: this likely isn’t possible; so I’m posting mostly as a thought experiment.

I’ve got some code that stores preferences (in Android, but I’ve generalized it below so that’s irrelevant):

object Config {
    private fun getPref(key: Int, default: Value): Boolean {
        // return the saved value, or `default` if no value has been saved
    }
    private fun putPref(key: Int, v: Value) {
        // save the value
    }
    var myPreference: Value
        get() = getPref(MY_KEY, DEFAULT_VALUE) // key and default value defined elsewhere
        set(value) = putPref(MY_KEY, value)

This allows me to write things like Config.myPreference = newValue. Thing is, I’ve got a fair number of preferences, all with the same getters/setters (but with different keys). It’d be nice if I could do something like this instead:

typeextension ValuePreference(private val key: Int, private val default: Value) : Value {
    override get() = getPref(key, default)
    override set(value) = setPref(key, value)
}

object Config {
   // Note the type
   var myPreference: Value = ValuePreference(MY_KEY, DEFAULT_VALUE)
}

Obviously I can make a class like the above with get() and set() functions, but then I have to use Config.myPreference.get() and Config.myPreference.set(newValue) instead of property access syntax. Thoughts on elegant ways to do this?

http://kotlinlang.org/docs/reference/delegated-properties.html

2 Likes