Skip to content

Instantly share code, notes, and snippets.

@numa08
Created March 30, 2020 14:02
Show Gist options
  • Save numa08/d759910155b18b8f59de6108198250fb to your computer and use it in GitHub Desktop.
Save numa08/d759910155b18b8f59de6108198250fb to your computer and use it in GitHub Desktop.
Type safe SharedPreferences
package net.numa08.typesafesharedpreferences
import android.content.SharedPreferences
sealed class Key<T> {
abstract val key: String
object Address : Key<String>() {
override val key: String = "address"
}
}
class Wrapper(private val preferences: SharedPreferences) {
fun <T> write(key: Key<T>, value: T) {
val editor = preferences.edit()
when (value) {
is String -> editor.putString(key.key, value)
// putXXX for float, int, long and StringSet
}
editor.apply()
}
fun <T> read(key: Key<T>, default: T? = null): T? {
@Suppress("UNCHECKED_CAST")
return preferences.all[key.key] as? T ?: default
}
}
@Suppress("UNREACHABLE_CODE")
fun test() {
val address = "Japan, Osaka"
val wrapper = Wrapper(preferences = TODO())
wrapper.write(Key.Address, address)
val saved = wrapper.read(Key.Address)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment