realm / realm-kotlin

Kotlin Multiplatform and Android SDK for the Realm Mobile Database: Build Better Apps Faster.
Apache License 2.0
915 stars 52 forks source link

custom setter function is not called #1803

Closed XilinJia closed 3 weeks ago

XilinJia commented 1 month ago

How frequently does the bug occur?

Always

Description

class Human: RealmObject {
    var name: String = ""
        set(value) {
           println("Example Setter called with value: $value")
           field = value
        }
}

When I set the name with: person.name = "John", the setter function is not called.

I googled hard to understand about the issue, it appears this 7 years old post explained it, but obviously is regarding the Java API, seems still valid with the current Kotlin API? https://stackoverflow.com/questions/43066612/realm-call-setter

Is it possible to get the setters to work in Kotlin as that's a neat feature of the language?

Stacktrace & log output

No response

Can you reproduce the bug?

Always

Reproduction Steps

No response

Version

2.0.0

What Atlas App Services are you using?

Local Database only

Are you using encryption?

No

Platform OS and version(s)

Android 9, Android 14

Build environment

Android Studio version: ... Android Build Tools version: ... Gradle version: ...

sync-by-unito[bot] commented 1 month ago

➤ PM Bot commented:

Jira ticket: RKOTLIN-1109

nirinchev commented 3 weeks ago

If you need to execute custom logic in the setter/getter of a property, you should @Ignore it so that it's not treated as persisted. So essentially, it should look something like this:

class Human: RealmObject {
    @Ignore
    public var name: String
        set(value) {
           println("Example Setter called with value: $value")
           name_persisted = value
        }
        get() {
            return name_persisted
        }

    private var name_persisted: String = ""