I would like to create an extension method that helps me validate that all lateinit
properties of a class have been initialized at a given point in time.
I have come up with the following so far:
fun Any.assertLateInitPropertiesAreInitialized() {
for (member in this::class.memberProperties) {
if (member.isLateinit) {
try {
member.call(this)
}
catch (e: Throwable) {
if (e.cause is UninitializedPropertyAccessException) {
throw e
}
}
}
}
}
but it's rather ugly because I have to call the property explicitly which may be quite expensive.
Is there a way to use isInitialized
instead? I can't figure out how to bind my KProperty1
to this
so as to get a KProperty0
so I access it (if it is at all possible).
As lateinit
properties cannot be nullable, it should be enough to check whether the Java field is null
. Something like:
member.javaField!!.get(this) != null