Created
March 30, 2020 14:02
-
-
Save numa08/d759910155b18b8f59de6108198250fb to your computer and use it in GitHub Desktop.
Type safe SharedPreferences
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
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