gpt4 book ai didi

java - 方法引用中的返回类型错误 : Cannot convert Employee to Optional

转载 作者:行者123 更新时间:2023-11-30 05:26:17 25 4
gpt4 key购买 nike

我正在尝试编写一个 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>直到这个操作。

关于java - 方法引用中的返回类型错误 : Cannot convert Employee to Optional<U>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58528976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com