Java 8 map signature: public<U> Optional<U> map(Function<? super T, ? extends U> mapper)--why are there two Us?

Viewed 1110
public<U> Optional<U> map(Function<? super T, ? extends U> mapper)

why are there two Us?

I understand the second U...The optional has a parameter describing the kind of Optional being returned.

But I don't get what the leading U is about. I'm struggling with call on the map method of optional with the following:

[javac]  return LocationAPIResponse.map(response -> Context.LocationContext.builder()...
[javac]                                            ^
[javac]  no instance(s) of type variable(s) U exist so that Optional<U> conforms to LocationContext
[javac]  where U,T are type-variables:
[javac]     U extends Object declared in method <U>map(Function<? super T,? extends U>)
[javac]     T extends Object declared in class Optional

I'm confused because the function I'm defining in map returns a LocationContext created by a builder. I'm confused by the two 'U's. Why is the compiler complaining

edit, fleshing out code sample to be more complete:

Optional<LocationServiceResponse> locationAPIResponse = locationServiceProxy.getLocation(locationServiceRequest);
    return locationAPIResponse.map(response -> Context.LocationContext
        .builder()
       .isNearby(response.getProximity().equals(ProxyEnum.NEARBY) ? 1 : 0)
       .lat(response.getLatitude().orElse(0))
       .lng(response.getLongitude().orElse(0))
       .build());
2 Answers

This simply the syntax for a method-local generic type.

By declaring it directly in the method signature, that U is bound to the context of this method.

You use that in situations where the generic parameter can or should not be known on class level (for example when you have a static method that needs generic parameters).

For the compiler error, we need more information. The only thing we can say so far: the signature of the method that uses the given return statement return locationAPIResponse.map() ... doesn't match what your mapper is returning!

Related