Search code examples
androidkotlingeolocation

Kotlin: Cannot reassign LatLng's latitude/longitude


Let's say I have 2 LatLng variables.

lateinit var mLatLng1:LatLng
lateinit var mLatLng2:LatLng

Let's say they've both already been initialized to some values.

If I try this:

mLatLng1 = mLatLng2

It works as expected. However, when i try this:

mLatLng1.latitude = mLatLng2.latitude

I get an error:

Val cannot be reassigned

If my mLatLng1 variable is of type var, then why am I getting this error?


Solution

  • If my mLatLng1 variable is of type var, then why am I getting this error?

    Because you are not assigning something to mLatLng1. That would be:

    mLatLng1 = LatLng(45.0, 123.0)
    

    Instead, you are doing this:

    mLatLng1.latitude = mLatLng2.latitude
    

    This is attempting to update a field inside mLatLng1. And, if your object is this LatLng, those fields are final, which in Kotlin maps to val.