Skip to content

Instantly share code, notes, and snippets.

@PetkevichPavel
Last active May 3, 2020 22:02
Show Gist options
  • Save PetkevichPavel/33b07a7801d27f25dde19e4aac45f13b to your computer and use it in GitHub Desktop.
Save PetkevichPavel/33b07a7801d27f25dde19e4aac45f13b to your computer and use it in GitHub Desktop.
SharedPreferences under Delegated properties - PreferencesDelegate putAny.
/**
* SharedPreferences.Editor extension function for putting [value] as Any into Shared preferences.
* @param key - key for the value.
* @param value - value as Any.
*/
@Suppress("UNCHECKED_CAST")
fun SharedPreferences.Editor.putAny(key: String, value: Any) {
when {
Generic<String>().checkType(value) -> (value as? String)?.let { putString(key, it) }
Generic<Boolean>().checkType(value) -> (value as? Boolean)?.let { putBoolean(key, it) }
Generic<Float>().checkType(value) -> (value as? Float)?.let { putFloat(key, it) }
Generic<Int>().checkType(value) -> (value as? Int)?.let { putInt(key, it) }
Generic<Long>().checkType(value) -> (value as? Long)?.let { putLong(key, it) }
Generic<Set<String>>().checkType(value) -> (value as? Set<String>)?.let {
putStringSet(key, it)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment