Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 961
Bhuvanesh BS Avatar asked Mar 08 '18 07:03

Bhuvanesh BS


1 Answers

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.

like image 83
Bhuvanesh BS Avatar answered Sep 22 '22 16:09

Bhuvanesh BS