Last active
June 14, 2020 13:20
-
-
Save kosratdev/030d2c3c36b20cfebafe0d14205a032a to your computer and use it in GitHub Desktop.
Better SharedPreferences with kotlin extensions
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
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