Skip to content

Instantly share code, notes, and snippets.

@laminr
Created June 1, 2018 13:26
Show Gist options
  • Select an option

  • Save laminr/8615f6ae795cc448f95ba09bf4872ee0 to your computer and use it in GitHub Desktop.

Select an option

Save laminr/8615f6ae795cc448f95ba09bf4872ee0 to your computer and use it in GitHub Desktop.
Kotlin extension for SharedPreferences
import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager
/**
*
* GET/SET
* val protectAtStart = defaultPrefs(context)["key", "defaultValue"]
* defaultPrefs(context)["key"] = "myValue"
*
* GET/SET w/ Anko inside an Actitivy/Fragment
* val protectAtStart = defaultSharedPreferences["key", "defaultValue"]
* defaultSharedPreferences["key"] = "myValue"
*
*/
fun defaultPrefs(context: Context): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
private inline fun SharedPreferences.edit(f: SharedPreferences.Editor.() -> Unit) {
val editor = edit()
editor.f()
editor.apply()
}
inline operator fun <reified T> SharedPreferences.get(key: String, defValue: T): T {
return when (T::class) {
Int::class -> getInt(key, defValue as Int) as T
String::class -> getString(key, defValue as String) as T
Boolean::class -> getBoolean(key, defValue as Boolean) as T
Long::class -> getLong(key, defValue as Long) as T
else -> defValue
}
}
operator fun SharedPreferences.set(key: String, value: Any?) {
when (value) {
is String -> edit({ putString(key, value) })
is Int -> edit({ putInt(key, value) })
is Boolean -> edit({ putBoolean(key, value) })
is Float -> edit({ putFloat(key, value) })
is Long -> edit({ putLong(key, value) })
else -> throw UnsupportedOperationException("Not yet implemented")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment