【问题标题】:Bad return type in method reference: Cannot convert Employee to Optional<U>方法参考中的错误返回类型:无法将 Employee 转换为 Optional<U>
【发布时间】:2019-10-23 18:25:56
【问题描述】:

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

但是对于我的 lambda 函数,我在 flatMap(this::buildEmployeeGeolocation) 处遇到编译错误 说Bad return type in method reference: cannot convert com.abc.EmployeeGeolocation to java.util.Optional&lt;U&gt;。

我在这里错过了什么?

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();
}

【问题讨论】:

    标签: java lambda optional flatmap


    【解决方案1】:

    看来您真正需要做的是交换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) 推断,在此操作之前它会导致Optional&lt;String&gt;。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多