4 ms·
>But sometimes it really is nice to be able to check if a field has already been initialized, which you can't do here. If you need a run-time check to figure o
by realharo 10y ago
>But sometimes it really is nice to be able to check if a field has already been initialized, which you can't do here.
If you need a run-time check to figure out whether a supposedly non-nullable field has been initialized, that sounds like a code smell to me.
I see the fact that something can only be initialized late as an internal matter of a library/module/part of project/etc. that should never leak outside of it (i.e. the outside world should never have to deal with potentially uninitialized objects - if it has to, then the field is not really non-nullable).
- afastow 10y agoAgreed. If you need to find out if a lateinit field has actually been initialized, and you aren't writing a library that is responsible for initializing it, that means your field is really nullable so just mark it as such. If you are writing a library I think you should be able to use reflection to figure out if it has actually been initialized, or worst case scenario just catch the exception that is thrown if it isn't initialized.
- norswap 10y agoBasically, complex initialization logic, when a field can be initialized in multiple different ways. Once the initialization step is complete, the field will never be null and no checking will be required ever again. But in the current state of affairs, you just have to make it nullable and sprinkle the `!!` operator all over your code.
- vbezhenar 10y agoUse two properties. First is nullable and holds real value, so you can check it. Second is non-nullable and just a getter for first.