I'm migrating a project from java to kotlin, and that project used a lot of variables that can be null and they are not initialized until some interaction with the user or external jobs have been done.
I'm trying to use kotlin null safety advantages, and I'm trying to avoid the use of null
in the source code, so i'm dealing with all the variables using lateinit
, like this: lateinit var location: Location
instead of using var location: Location? = null
I'm doing it to avoid using ?
each time I need to use those variables. The issue now is... what happens if the variables has been not initialized?
For example, what happens if I need to call location.getX()
in some part of the code? How to deal with cases in which location is still not initialized?
I figured out to deal with it using this:
if (!this::location.isInitialized){
location.getX()
}
But then, I'm filling the code with that boilerplate code of isInitialized etc... so... at the end, I prefeer the old java version of the project without null safety, it's more clear and short.
If I come back to var location: Location? = null
, then, I need to use
location.let {
it.getX()
}
or
location?.getX()
and in this second case I'm still dealing with null, that is something I was trying to avoid
Is something I'm doing wrong? must I come back to null variables and var location: Location? = null
instead of using lateinit
? Exists a better approach to do this?