方法参考中的错误返回类型:无法将Employee转换为Optional

问题描述 投票:1回答:1

我正在尝试编写一个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();
    }
java lambda optional flatmap
1个回答
0
投票

flatMap需要一个Function<? super T, Optional<U>>映射器,但是您要传递的映射器(this::buildEmployeeGeolocation)不会返回Optional,它会返回一个EmployeeGeolocation。也许您应该改用map

更改

.flatMap(this::buildEmployeeGeolocation)

to

.map(this::buildEmployeeGeolocation)
© www.soinside.com 2019 - 2024. All rights reserved.