Skip to content

Instantly share code, notes, and snippets.

@tobiasschuerg
Created October 20, 2018 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tobiasschuerg/4d19161638f8dd5d7551b58ab96c353d to your computer and use it in GitHub Desktop.
Save tobiasschuerg/4d19161638f8dd5d7551b58ab96c353d to your computer and use it in GitHub Desktop.
Kotlin Delegate for persistant objects
package com.tobiasschuerg
import android.content.SharedPreferences
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class GsonDelegatePref<T>(
private val prefs: SharedPreferences,
private val name: String,
private val typeOfT: Class<T>,
private val default: (() -> T?) = { null }
) : ReadWriteProperty<Any?, T?> {
override fun getValue(thisRef: Any?, property: KProperty<*>): T? {
val json: String? = prefs.getString(name, null)
return if (json != null) {
gson.fromJson(json, typeOfT)
} else {
default()
}
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
val json: String? = value?.let { gson.toJson(value) }
prefs.edit().putString(name, json).apply()
}
companion object {
private val gson: Gson = GsonBuilder().setPrettyPrinting().create()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment