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

我正在尝试编写一个 lambda 函数来获取员工位置偏好并具有下面的代码示例。


flatMap(this::buildEmployeeGeolocation) 但对于我的 lambda 函数,我在说 时遇到编译错误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();

}


qq_遁去的一_1
浏览 140回答 1
1回答

三国纷争

看来您真正需要做的是交换map和flatMap。更改代码.map(this::readEmployeeLocation)&nbsp; .flatMap(this::buildEmployeeGeolocation);到.flatMap(this::readEmployeeLocation)&nbsp;//&nbsp;since&nbsp;you&nbsp;already&nbsp;have&nbsp;an&nbsp;Optional<String> .map(this::buildEmployeeGeolocation);&nbsp;//&nbsp;above&nbsp;results&nbsp;in&nbsp;Optional<EncryptedGeolocation>重要提示:从代码中推断Optional.ofNullable(...).map(...).filter(StringUtils::isNotBlank),它将导致Optional<String>直到此操作。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java