The ?
in your code on the values mean that those certain params can be null.
locationComponent.lastKnownLocation?.latitude?.toDouble()
This locationComponent.lastKnownLocation?
means that lastKnownLocation
can be null, and thus latitude
can be null (latitude can also be null by itself, I don't know since I can't see the model).
Point.fromLngLat(lat, lng)
does not accept null values, that means that you need to be cautious here.
You can fix this by checking the code to see if lastKnownLocation
can truly be null, or is it just a non-annotated java param so the compiler doesn't how to treat it, so it plays it safe.
In that particular case (when you know for a fact that it can't be null) you can use !!
to declare that value as not null (but this will throw a NPE if you are wrong).
You can also try and mitigate the risk by providing a default value, but then, what do you do with that default value? In what part of the world do you assign it to? Maybe you have other location components that would make sense, like the middle of the country of residence or etc (it all depends on the rest of your code).
val lat = locationComponent.lastKnownLocation?.latitude?.toDouble() ?: 0.0
val lng = locationComponent.lastKnownLocation?.longitude?.toDouble() ?: 0.0
Here, lat
and lng
will be set to 0.0
if they are null.
But depending on your cases you might actually want to not make that call when you don't have values. So you can try and check if they are null beforehand.
val lat = locationComponent.lastKnownLocation?.latitude?.toDouble()
val lng = locationComponent.lastKnownLocation?.longitude?.toDouble()
if(lat != null && lng != null) origin = Point.fromLngLat(lat, lng)
But in this scenario your origin is not set. But if those values can truly be null, then maybe that origin makes sense to not be set.
I strongly recommend that you read this: Null Safety in Kotlin