Can you confirm that Delegated Properties are acce...
# reflect
d
Can you confirm that Delegated Properties are accessed only when the variable is read. For example in this context:
Copy code
object 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
?
d
The expression on the right side of
by
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:
Copy code
object LocalSettings : SettingsClass() {
  private val myStringDelegate = StringType("mytext")
  var myString
    get() = myStringDelegate.getValue(this, LocalSettings::myString)
    set(value) {
      myStringDelegate.setValue(this, LocalSettings::myString, value)
    }
d
OK, great, so it looks like it’s behaving the way I meant. Many thanks