Skip to content

Instantly share code, notes, and snippets.

@AlvarezAriel
Created March 11, 2015 16:00
Show Gist options
  • Select an option

  • Save AlvarezAriel/26c4d39819852d17ddf8 to your computer and use it in GitHub Desktop.

Select an option

Save AlvarezAriel/26c4d39819852d17ddf8 to your computer and use it in GitHub Desktop.
DelegatedPreference
public class DelegatedPreference<T>(val default: T, val preferencesManagerInstantiator:()->SharedPreferences) {
val manager : SharedPreferences by Delegates.lazy(preferencesManagerInstantiator)
[suppress("UNCHECKED_CAST")]
fun get(thisRef: Any?, prop: PropertyMetadata): T {
return when(default){
is Int -> manager.getInt(prop.name, this.default) as T
else -> throw TypeNotImplementedException(prop.name)
}
}
fun set(thisRef: Any?, prop: PropertyMetadata, value: T) {
when(value){
is Int -> manager.edit().putInt(prop.name, value ).apply()
else -> throw TypeNotImplementedException(prop.name)
}
}
class TypeNotImplementedException(val propName:String) : Exception("Type of ${propName} is not implemented on DelegatedPreference and thus invalid")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment