realm / realm-kotlin

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

Support single primary constructor models #783

Open jakobkmar opened 2 years ago

jakobkmar commented 2 years ago

It would be great if the following works:

class TestModel(
    var firstName: String,
    var lastName: String,
    var age: Int
) : RealmObject

This was already mentioned in other issues like #184 but I wanted to create a tracking issue for the feature.

The advantage would be that it is not possible to miss any properties when creating an instance of the model. Additionally, the variables don't have to be initialized with placeholder values in the code.

cmelchior commented 2 years ago

Hi @jakobkmar. We fully agree that being able to get to something like you post there, would be ideal. The problem we have is that we need to be able to instantiate objects on behalf of you when reading out objects again from Realm.

This means that we need to be able to provide default values for all the parameters in the constructor.

Right now, when we only support a limited set of property types, that should actually be doable. But we also want to add support for custom type adapters (https://github.com/realm/realm-kotlin/issues/587), which makes this a lot more complicated.

But we might be able to find a middle ground where constructors with "simple" types are supported, while more advanced types would need a empty no-arg constructor.

Another alternative might be to use the compiler plugin to hack the visibility of the constructor so something like this:

class TestModel(
    var firstName: String,
    var lastName: String,
    var age: Int
) : RealmObject {
  private constructor(): this("", "", 0)
}

But that would also be kinda annoying and doesn't feel very natural.

jakobkmar commented 2 years ago

Is it maybe a possibility that custom type adapters (optionally) define a default value for instantiating the variables which can then be used if no default values and no secondary no-arg constructor are given?

cmelchior commented 2 years ago

Yes, that would also be a way we could enable the use of more advanced types in constructors 👍