260
260

Reputation: 33

java: Is there any way to avoid writing named class? (variable has not been initialized)

In one place (and only one) i need a wrapper around the interface passed to the method. If possible I would like to avoid complicating the code by writing separate class for that purpose, so I wanted to take a closure approach, but then I run into "variable may not have been initialized" error.

I've found similar problem ( Final Local Variable may not have been initialized in anonymous inner class ), but If possible I would like to find a way to go around the problem without writing separate class for the wrapper.

the code:

    protected void startListening(LocationRequest request,@Nullable final LocationListener listener) {
    ...
    final LocationListener l = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            if(listener != null) {
                listener.onLocationChanged(location);
            }
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, l);
        }
    };
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, request, l);
}

Additional details:

Upvotes: 2

Views: 100

Answers (2)

RealSkeptic
RealSkeptic

Reputation: 34638

As usual in Java, when you have an initializer (or any assignment statement), first the expression to assign is calculated, and only then it is assigned to the variable.

This is also true for your local variable l - at the time you create the anonymous class, l does not yet have a value - it will only have one after the instance of the anonymous class has been constructed and assigned to it.

So of course, you can't refer to an uninitialized variable from a closure, and that's the reason for the issue you had.

The solution is to use this to refer to that instance from inside it, rather than using l. You can use this in anonymous classes, as opposed to lambda expressions, in which this refers to the enclosing class.

Upvotes: 3

E-Riz
E-Riz

Reputation: 33004

Instead of trying to pass the local variable l to removeLocationUpdates(), which is what triggers the error, just pass this as the argument. That works because in the context of that anonymous class, this refers to the anonymous class instance(LocationListener)

LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);

Upvotes: 1

Related Questions