Last active
December 9, 2018 18:25
-
-
Save ViksaaSkool/84724bab8ae3d832e36064abb01c989a to your computer and use it in GitHub Desktop.
Example for Kotlin Generics - MyKotlinSharedPreference call when storing/retrieving any type of primitive data
This file contains 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
//One very powerful example of Generics might in combination with delegates is creation of SharedPreferences support | |
//taken from Kotlin for Android Developers by Antonio Leiva | |
class MyKotlinSharedPreference<T>(val context: Context, val name: String, val default: T) { | |
val prefs by lazy { | |
context.getSharedPreferences("default", Context.MODE_PRIVATE) | |
} | |
//operator overloading | |
operator fun getValue(thisRef: Any?, property: KProperty<*>): T { | |
return findPreference(name, default) | |
} | |
//operator overloading | |
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { | |
putPreference(name, value) | |
} | |
//use when yo distingush type | |
private fun <T> findPreference(name: String, default: T): T = with(prefs) { | |
val res: Any = when (default) { | |
is Long -> getLong(name, default) | |
is String -> getString(name, default) | |
is Int -> getInt(name, default) | |
is Boolean -> getBoolean(name, default) | |
is Float -> getFloat(name, default) | |
else -> throw IllegalArgumentException("This type can't be saved into Preferences") | |
} | |
res as T | |
} | |
//use when yo distingush type | |
private fun <U> putPreference(name: String, value: U) = with(prefs.edit()) { | |
when (value) { | |
is Long -> putLong(name, value) | |
is String -> putString(name, value) | |
is Int -> putInt(name, value) | |
is Boolean -> putBoolean(name, value) | |
is Float -> putFloat(name, value) | |
else -> throw IllegalArgumentException("This type can be saved into Preferences") | |
}.apply() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment