Created
March 11, 2015 16:00
-
-
Save AlvarezAriel/26c4d39819852d17ddf8 to your computer and use it in GitHub Desktop.
DelegatedPreference
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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