Daniele B
08/14/2020, 1:35 AMobject LocalSettings : SettingsClass() {
var myString by StringType("mytext")
}
open class SettingsClass {
val settings = Settings()
inner class StringType(defaultValue : String) {
val default = defaultValue
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
return settings.getString(property.name, default)
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
settings.putString(property.name, value)
}
}
}
can you confirmed that when the LocalSettings object is instantiated, the StringType
delegate will be called only when accessing LocalSettings.myString
?diesieben07
08/14/2020, 7:12 AMby
will be evaluated at construction time, i.e. when LocalSettings
is instantiated (or in your case, because LocalSettings
is an object, when it's class is loaded, which requires JVM details to know exactly when it happens, but basically it's when it's first accessed).
The getValue
and setValue
will only be called when you get resp. set the myString
property.
You can think of by
being translated like this:
object LocalSettings : SettingsClass() {
private val myStringDelegate = StringType("mytext")
var myString
get() = myStringDelegate.getValue(this, LocalSettings::myString)
set(value) {
myStringDelegate.setValue(this, LocalSettings::myString, value)
}
Daniele B
08/14/2020, 11:29 AM