When I want to use lambda to call a method in another Service.java and then use it as the condition to decide return value. It always said "unexpected return value" in lambda. How can I return it?
public SortOrder transform(SortOrder sort, String abc) {
if (sort == null) {
return SortOrder.A;
} else if (sort.equals(SortOrder.B) && abc != null) {
return AnotherService.getString(abc)
.map(l -> l.ifPresent(m -> {
if (m.getName().equals("name")) {
return SortOrder.C; //ERROR: unexpected return value
}
return sort; //ERROR: unexpected return value
}));
} else {
return sort;
}
return sort;
}
The function Optional.ifPresent accepts a consumer, which isn't allowed to return a value at all. The lambda passed to ifPresent must have void return type.
You're probably best off not using a lambda for that part, and instead writing if (l.isPresent()) { ... }.
If you insist on using the functional style, you could write l -> l.filter(m -> m.getName().equals("name")).map(l -> SortOrder.C).orElse(sort).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With