错误 return 方法引用中的类型:无法将 Employee 转换为 Optional<U>

Bad return type in method reference: Cannot convert Employee to Optional<U>

我正在尝试编写一个 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::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();
}

看来您真正需要做的是交换 mapflatMap。更改代码

.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) 推断,它将导致 Optional<String> 直到操作。