DEV Community

Discussion on: Safely accessing lateinit properties in Kotlin

Collapse
 
neokleoys2005 profile image
Giorgos Neokleous • Edited

So, you are using lateinit, which offers immutable objects, but you still have to surround it with conditional checks (which checks are being done using reflection).

How is this better and "not the rookie" way?

In my opinion it depends on the situation. If you find yourself having to make lateinit properties either nullable or having to wrap them with #isInitialized then you need to rethink your architecture. It always depends on the problem you are trying to solve ofc.

Reflection is expensive and it shouldn't be the rule of thumb to use over nullable properties.

Collapse
 
rahulchowdhury profile image
Rahul Chowdhury 🕶

Hey Giorgos, this might not be the best way to approach the "empty state" issue but it's certainly a neat trick that you can apply using the Kotlin standard library.

How you approach the problem and architect your application differs from person to person, isn't it?

This is just one way of doing it. :-)

Collapse
 
neokleoys2005 profile image
Giorgos Neokleous

Of course it depends on the person and the team. I think you shouldn't put the label

Taking the rookie approach

For wrapping properties with is not null conditions. On runtime the null check is theoretically faster than the approach described above.

Another way of solving it, it's to design the application in such way that race condition doesn't happen. Try and access the property when and only when is initialised and not before that. So that you avoid such issues.