Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix "unexpected return value" when using lambda?

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;
  }
like image 622
Lena Avatar asked Jun 07 '26 06:06

Lena


1 Answers

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).

like image 62
Louis Wasserman Avatar answered Jun 10 '26 04:06

Louis Wasserman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!