Search code examples
androidkotlinrealm

Kotlin Realm: Class must declare a public constructor with no arguments if it contains custom constructors


I'm creating a Realm object in Kotlin.

Realm Object:

open class PurposeModel(var _id: Long?,
                        var purposeEn: String?,
                        var purposeAr: String?) : RealmObject()

When I compile the above code I'm getting this error:

error: Class "PurposeModel" must declare a public constructor with no arguments if it contains custom constructors.

I can't find any question related to this in Kotlin. How do I resolve this?


Solution

  • To clear this error you have to assign default values to properties.

    Change the Realm Object like this:

    open class PurposeModel(
        var _id: Long? = 0,
        var purposeEn: String? = null,
        var purposeAr: String? = null
    ) : RealmObject()
    

    Now it will compile.

    Reason:

    When the default value not assigned it will become the parameters of the constructor, Realm need a public constructor with no arguments. When the default value assigned, it will become the properties of the class. So you will get empty constructor by default and clean code.