Skip to content

Instantly share code, notes, and snippets.

@worker8
Created November 19, 2018 02:57
Show Gist options
  • Save worker8/aa074d1ba0057e0919868517f139da5e to your computer and use it in GitHub Desktop.
Save worker8/aa074d1ba0057e0919868517f139da5e to your computer and use it in GitHub Desktop.
A Kotlin share preference helper
import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager
fun Context.defaultPrefs(): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
fun Context.customPrefs(name: String): SharedPreferences = getSharedPreferences(name, Context.MODE_PRIVATE)
fun SharedPreferences.save(key: String, value: Any) {
edit().apply {
when (value) {
is String -> putString(key, value)
is Int -> putInt(key, value)
is Boolean -> putBoolean(key, value)
is Float -> putFloat(key, value)
is Long -> putLong(key, value)
else -> throw UnsupportedOperationException("Unsupported Type")
}
}.apply()
}
inline fun <reified T : Any> SharedPreferences.get(key: String, defaultValue: T): T {
defaultValue.ofType<String> {
return getString(key, it) as T
}
defaultValue.ofType<Int> {
return getInt(key, it) as T
}
defaultValue.ofType<Boolean> {
return getBoolean(key, it) as T
}
defaultValue.ofType<Float> {
return getFloat(key, it) as T
}
defaultValue.ofType<Long> {
return getLong(key, it) as T
}
throw UnsupportedOperationException("Unsupported Type")
}
inline fun <reified T> Any.ofType(block: (T) -> Unit) {
if (this is T) {
block(this as T)
}
}
// example usage
// onCreate() {
// val pref = defaultPrefs()
// pref.save("key", "value") // set
// pref.get("key", "defaultValue") // get
// pref.edit().remove("first").apply() // remove
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment