public<U> Optional<U> map(Function<? super T, ? extends U> mapper)
为什么有两个 U?
我理解第二个 U...可选项具有描述返回的可选项类型的参数。
但我不明白前导的 U 是什么意思。我在调用带有以下内容的可选项的 map 方法时遇到了困难:
[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中定义的函数返回一个由builder创建的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());
map
的函数预期执行什么操作? 考虑它返回一个 Optional ,这对于map
操作很奇怪(其名称来自函数式编程)。此外,.build()
的返回类型是什么? - Ryan Leachmap()
方法。 - GhostCatreturn locationAPIResponse.map()
的方法的签名也很重要。关键是编译器无法将您对map()
的使用与使用返回值的方法的签名“连接”起来! - GhostCat