Skip to content

Instantly share code, notes, and snippets.

@e4basil
Created March 21, 2023 08:31
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 e4basil/54956a79b4f771e08b09992608d07a36 to your computer and use it in GitHub Desktop.
Save e4basil/54956a79b4f771e08b09992608d07a36 to your computer and use it in GitHub Desktop.
Extension functions for getting and putting values in SharedPreferences:
inline fun <reified T : Any> SharedPreferences.get(key: String, defaultValue: T? = null): T? {
val value = when (T::class) {
String::class -> getString(key, defaultValue as? String) as T?
Int::class -> getInt(key, defaultValue as? Int ?: -1) as T?
Long::class -> getLong(key, defaultValue as? Long ?: -1L) as T?
Float::class -> getFloat(key, defaultValue as? Float ?: -1f) as T?
Boolean::class -> getBoolean(key, defaultValue as? Boolean ?: false) as T?
else -> throw IllegalArgumentException("Unsupported type: ${T::class.java}")
}
return value
}
inline fun <reified T : Any> SharedPreferences.put(key: String, value: T?) {
val editor = edit()
when (T::class) {
String::class -> editor.putString(key, value as? String)
Int::class -> editor.putInt(key, value as? Int ?: -1)
Long::class -> editor.putLong(key, value as? Long ?: -1L)
Float::class -> editor.putFloat(key, value as? Float ?: -1f)
Boolean::class -> editor.putBoolean(key, value as? Boolean ?: false)
else -> throw IllegalArgumentException("Unsupported type: ${T::class.java}")
}
editor.apply()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment