Java 8 映射签名:公共可选映射<U> <U> (功能<?超级T,?扩展U>映射器)--为什么有两个我们?


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

为什么有两个我们?

我理解第二个U…optional有一个参数,描述返回的optional的类型

但我不明白U是怎么回事。我很难在地图上调用可选的方法,如下所示:

[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

我很困惑,因为我在map中定义的函数返回了一个生成器创建的LocationContext。我被两个U弄糊涂了。为什么编译器抱怨

编辑,充实代码样本以更完整:

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());

这只是方法本地泛型类型的语法。

通过在方法签名中直接声明它,U被绑定到该方法的上下文。

在类级别上可以或不应该知道泛型参数的情况下(例如,当您有一个需要泛型参数的静态方法时(,可以使用它。

对于编译器错误,我们需要更多信息。到目前为止,我们只能说:使用给定返回语句return locationAPIResponse.map() ...的方法的签名与映射程序返回的内容不匹配!

第一个U是泛型方法所需的语法,Optional中的第二个U是一个泛型类和将在此方法上下文中使用泛型类型U作为参数的返回类型。请参阅文档了解更多信息https://docs.oracle.com/javase/tutorial/extra/generics/methods.html

最新更新