Skip to content

Instantly share code, notes, and snippets.

@tuyen-vuduc
Created March 25, 2018 04:38
Show Gist options
  • Save tuyen-vuduc/e6119b0a4d24bc982face9700c806a3b to your computer and use it in GitHub Desktop.
Save tuyen-vuduc/e6119b0a4d24bc982face9700c806a3b to your computer and use it in GitHub Desktop.
SharedPreferencesExtensions - Kotlin
import android.content.SharedPreferences
inline fun <reified T> SharedPreferences.get(key: String, defaultValue: T): T {
when(T::class) {
Boolean::class -> return this.getBoolean(key, defaultValue as Boolean) as T
Float::class -> return this.getFloat(key, defaultValue as Float) as T
Int::class -> return this.getInt(key, defaultValue as Int) as T
Long::class -> return this.getLong(key, defaultValue as Long) as T
String::class -> return this.getString(key, defaultValue as String) as T
else -> {
if (defaultValue is Set<*>) {
return this.getStringSet(key, defaultValue as Set<String>) as T
}
}
}
return defaultValue
}
inline fun <reified T> SharedPreferences.put(key: String, value: T): T {
val editor = this.edit()
when(T::class) {
Boolean::class -> editor.putBoolean(key, value as Boolean)
Float::class -> editor.putFloat(key, value as Float)
Int::class -> editor.putInt(key, value as Int)
Long::class -> editor.putLong(key, value as Long)
String::class -> editor.putString(key, value as String)
else -> {
if (value is Set<*>) {
editor.putStringSet(key, value as Set<String>)
}
}
}
editor.commit()
}
@artsok
Copy link

artsok commented Sep 22, 2020

great!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment