Search code examples
realmkotlin

Realm call setter


I'm using realm as database and kotlin as language.
I implemented my custom setter method for a property.

Does Realm call this setter somehow?

For example:

open class Human(): RealmObject()
{
    open var Name: String = ""
    set(value) 
    {
       setName(value)
    }
}

Now I also have a property changeDate and it would be nice if I can set the changeDate automatically in the setNameto new actual day.

But I can't do this if Realm calls this method also.

Thanks


Solution

  • I've tried this with Kotlin 1.1.1 and Realm 3.0.0, and it doesn't call the custom setter, it assigns the value in some other way (which means that it even works if your custom setter is empty, which is a bit unexpected).

    Edit: Looked at the generated code and the debugger.

    When you're using an object that's connected to Realm, it's an instance of a proxy class that's a subclass of the class that you're using in your code. When you're reading properties of this instance, the call to the getter goes down to native calls to access the stored value that's on disk, inside Realm.

    Similarly, calling the setter eventually gets to native calls to set the appropriate values. This explains why the setter doesn't get called: Realm doesn't need to call the setter, because it doesn't load the values into memory eagerly, the proxy is just pointing into the real data in Realm, and whenever you read that value, it will read it from there.

    As for how this relates to Kotlin code, the calls to the proxy's setter and getter that access the data inside Realm happen whenever you use the field keyword (for the most part).

    var Name: String = ""
        get() {
            return field // this calls `String realmGet$Name()` on the proxy
        }
        set(value) {
            field = value // this calls `void realmSet$Name(String value)` on the proxy
        }