realm-java icon indicating copy to clipboard operation
realm-java copied to clipboard

Kotlin: Private fields are Nullable in database even if property is marked as non-null

Open Sh0rxy opened this issue 5 years ago • 3 comments

Goal

Use private fields to store custom types or enums. For example:

//Foo.kt

enum class MyEnum {
    FOO
}

open class Foo: RealmObject() {

    private var _enum: String = MyEnum.FOO.name
    var enum: MyEnum
        get() { return MyEnum.valueOf(_enum) }
        set(value) { _enum = value.name }
    

    var myString : String = "myString"
}

Actual Results

When the Kotlin code gets compiled into Java bytecode, the field _enum``{{ won't be annotated with }}``@NotNull. As a consequence the field _enum in the database will be nullable.

Steps & Code to Reproduce

Create the file Foo.kt in Android Studio and run your project. Afterwards you can copy your myRealm.realm``{{ file from }}``/data/data/com.example.myProject/files/myRealm.realm``{{ via the Device File Explorer to your computer and open the file via RealmStudio. In the class Foo the field }}``_enum``{{ will not be }}``String``{{, but }}``String?

Version of Realm and tooling

Realm version(s): 6.1.0

Realm Sync feature enabled: No

Kotlin version 1.3.72

Android Studio version: 3.6.3

Which Android version and device: Any device minSdkVersion 21 targetSdkVersion 29 compileSdkVersion 29

Android Build Tools version: 29.0.3

Gradle version: 5.6.4

Sh0rxy avatar May 07 '20 17:05 Sh0rxy

Hmm, that sounds odd. The String should be non-null in Kotlin. Will investigate.

cmelchior avatar May 07 '20 17:05 cmelchior

I also posted a question on SO as to why this occurs, since this happens not only for Realm, but in general when using private properties in a class. Private String properties are nullable in decompiled .java class Kotlin

Sh0rxy avatar May 07 '20 18:05 Sh0rxy

We can probably detect this by looking at the Kotlin metadata instead of relying on the @NotNull annotation being present.

In the meantime, you can manually add the @Required annotation.

cmelchior avatar May 29 '20 15:05 cmelchior