我正在尝试编写一个lambda函数,该函数可获取员工的位置偏好设置并在下面提供代码示例。
但是对于我的lambda函数,我在flatMap(this::buildEmployeeGeolocation)
处遇到了编译错误说Bad return type in method reference: cannot convert com.abc.EmployeeGeolocation to java.util.Optional<U>
。
我在这里想念什么?
public Optional<EmployeeGeolocation> getEmployee
(
final SessionId sessionId
)
{
return Optional.ofNullable
(
employeePreferencesStore.getEmployeeAccountPreferences(sessionId)
).map
(
preferences -> preferences.getPreference(PreferenceKey.Location)
)
.filter(StringUtils::isNotBlank)
.map(this::readGeolocation)
.flatMap(this::buildEmployeeGeolocation)
;
}
private Optional<EncryptedGeolocation> readEmployeelocation
(
@NonNull final String encryptedGeolocation
)
{
try {
return Optional.ofNullable(objectMapper.readValue(encryptedGeolocation, EmployeeGeolocation.class));
}
catch (final IOException e) {
log.error("Error while reading the encrypted geolocation");
throw new RuntimeException(e);
}
}
private EmployeeGeolocation buildEmployeeGeolocation
(
@NonNull final EncryptedGeolocation unditheredEncryptedGeolocation
)
{
return EmployeeGeolocation.builder()
.latitude(10.0)
.longitude(10.0)
.accuracy(1.0)
.locationType(ADDRESS)
.build();
}
flatMap
需要一个Function<? super T, Optional<U>>
映射器,但是您要传递的映射器(this::buildEmployeeGeolocation
)不会返回Optional
,它会返回一个EmployeeGeolocation
。也许您应该改用map
。
更改
.flatMap(this::buildEmployeeGeolocation)
to
.map(this::buildEmployeeGeolocation)