我正在嘗試編寫一個(gè) lambda 函數(shù)來獲取員工位置偏好并具有下面的代碼示例。flatMap(this::buildEmployeeGeolocation) 但對于我的 lambda 函數(shù),我在說 時(shí)遇到編譯錯(cuò)誤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::readEmployeelocation) .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();}
1 回答

三國紛爭
TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超7個(gè)贊
看來您真正需要做的是交換map
和flatMap
。更改代碼
.map(this::readEmployeeLocation) .flatMap(this::buildEmployeeGeolocation);
到
.flatMap(this::readEmployeeLocation) // since you already have an Optional<String> .map(this::buildEmployeeGeolocation); // above results in Optional<EncryptedGeolocation>
重要提示:從代碼中推斷Optional.ofNullable(...).map(...).filter(StringUtils::isNotBlank)
,它將導(dǎo)致Optional<String>
直到此操作。
添加回答
舉報(bào)
0/150
提交
取消