항상 새로운 객체를 만들고 하다보면 코드도 길어지고 이쁘지 않다.
그래서 어떻게 합칠까 생각하다가 아래의 코드를 고안해 냈다.
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){
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()
}
getSharedPreferences(getString(R.string.pref_name),MODE_PRIVATE)
.get(getString(R.string.isfirst), false)
getSharedPreferences(getString(R.string.pref_name),MODE_PRIVATE)
.put(getString(R.string.isfirst), true)
이런식으로 편하게 sharedpreference를 사용할수 있다.