7

I have two classes which might look like this

class MyClass {
    var myProperty: AnotherClass?
}

class AnotherClass {

}

Through reflection I iterate the properties of MyClass and when I find a KMutableProperty<*> which is null I want to create an instance of that class. Right now I'm doing something like this

val instance = MyClass()
val property = MyClass::myProperty
var subInstance = it.getter.call(instance)
if (subInstance == null) {
    it.setter.call(instance, property.returnType.jvmErasure.createInstance())
}

but this seems like a terrible hack that needs to know internals and use Java magic instead of being pure Kotlin, is there a proper way to do what I want? Or is this the proper way?

3
  • Is your goal specifically to initialize all null properties with calls to the default, no parameter constructors of the classes you need in those places?
    – zsmb13
    Mar 12, 2017 at 16:25
  • That's right, all of them will be POJO (POKO?) classes
    – Ritave
    Mar 12, 2017 at 18:07
  • 2
    I believe that there isn't currently a way to do this without making the jvmErasure call right now. I suppose that makes it the proper way.
    – zsmb13
    Mar 12, 2017 at 18:18

1 Answer 1

5

You can use (property.returnType.classifier as KClass).createInstance() instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.