Skip to content

Instantly share code, notes, and snippets.

@kosratdev
Last active June 14, 2020 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kosratdev/030d2c3c36b20cfebafe0d14205a032a to your computer and use it in GitHub Desktop.
Save kosratdev/030d2c3c36b20cfebafe0d14205a032a to your computer and use it in GitHub Desktop.
Better SharedPreferences with kotlin extensions
inline val Context.sharedPreferences: SharedPreferences
get() = PreferenceManager.getDefaultSharedPreferences(this)
inline fun <reified T> SharedPreferences.get(key: String, defaultValue: T): T {
return when (T::class) {
Boolean::class -> this.getBoolean(key, defaultValue as Boolean) as T
Float::class -> this.getFloat(key, defaultValue as Float) as T
Int::class -> this.getInt(key, defaultValue as Int) as T
Long::class -> this.getLong(key, defaultValue as Long) as T
String::class -> this.getString(key, defaultValue as String) as T
else -> defaultValue
}
}
inline fun <reified T> SharedPreferences.put(key: String, value: T) = edit {
when (T::class) {
Boolean::class -> putBoolean(key, value as Boolean)
Float::class -> putFloat(key, value as Float)
Int::class -> putInt(key, value as Int)
Long::class -> putLong(key, value as Long)
String::class -> putString(key, value as String)
else -> throw Exception("Not yet implemented")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment