how to make this code a templated one instead of j...
# getting-started
c
how to make this code a templated one instead of just supporting Int?
Copy code
class PreferenceAccessor(
    private val preference: SharedPreferences,
    private val key: String,
    private var field: Int = 0
) {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): Int {
        return preference.getInt(key, 0)
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) {
        var editor = preference.edit()
        editor.putInt(key, value)
        editor.apply()
        field = value
    }
}
s
Copy code
class PreferenceAccessor<T>(
    private val preference: SharedPreferences,
    private val key: String,
    private var field: T
) {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
        return when (field) {
            is Int -> preference.getInt(key, field as Int) as T
            is Long -> preference.getLong(key, field as Long) as T
            is Float -> preference.getFloat(key, field as Float) as T
            is Boolean -> preference.getBoolean(key, field as Boolean) as T
            is String -> preference.getString(key, field as String) as T
            else -> throw IllegalArgumentException("Unsupported type")
        }
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        val editor = preference.edit()
        when (value) {
            is Int -> editor.putInt(key, value)
            is Long -> editor.putLong(key, value)
            is Float -> editor.putFloat(key, value)
            is Boolean -> editor.putBoolean(key, value)
            is String -> editor.putString(key, value)
            else -> throw IllegalArgumentException("Unsupported type")
        }
        editor.apply()
        field = value
    }
}
Try this.
👍 1