Closed cmelchior closed 2 years ago
Would be great if this gets fixed, because doing
val person = Person().apply {
name = "Carlo"
dog = Dog().apply { name = "Fido"; age = 16 }
}
works, but it is easy to forget a property there without the compiler warning you, unlike with constructors.
Hi @jakobkmar. Just a quick thought. I think you should be able to get away with defining a secondary constructor like
class Dog() : RealmObject {
var name: String? = null
var age: Int? = null
constructor(name: String, age: Int) : this() {
this.name = name
this.age = age
}
}
This still enables you to forget calling the right constructor, but at least you will not miss single arguments and is way more compact. We don't have explicit unit test covering this, so might be that there can be corner cases that won't work, but I can not immediately think of why it shouldn't.
Thank you, this is a good workaround for the time being!
@cmelchior This is tricky to support since the compiler plugin provides the mediator with the ability to instantiate classes dynamically (without using reflection). The IR lowering references the first zero arg (primary) constructor, if the user doesn't define one it will be difficult to call the non-zero arg ctor with sensible default values (for example avoid generating default object with the same PK value)
Yes, but last I checked, I think we only support the no-arg constructor as the primary one...I suspect we could also support it as a secondary one, like this:
class Expression(expression: String) : RealmObject {
constructor(): this("")
var expressionString: String = expression
}
Yes we can support models like
class Expression(expression: String) : RealmObject {
constructor(): this("")
var expressionString: String = expression
}
but that's different from the initial issue use case
Does this mean
class ConstructorTest(var firstName: String, var lastName: String, var age: Int) : RealmObject
is now supported as well?
@jakobkmar no, you still need to provide a default zero arg constructor like explained in https://github.com/realm/realm-kotlin/issues/184#issuecomment-1031626034
The following model class is not currently supported by our Compiler Plugin. If there are restrictions on constructors we should attempt to lift them or document them.