Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning local variables inside a lambda expression

I'm trying to learn and understand the use of lambda expressions in Java.

I have written a function within a class that returns a boolean result based on an Optional value using a lambda expression.

private boolean isNullOrEmpty(Optional<String> value) {
  boolean result;
  value.ifPresent(v -> result = isEmptyOrWhitespace(v));

  return result;
} 

isEmptyOrWhitespace is a simple function I've defined elsewhere to check if a string is null or has only whitespace:

private boolean isEmptyOrWhitespace(String value) {
    return value == null || value.trim().isEmpty();

The issue is, I cannot compile this because the compiler says

variable used in lambda should be final or effectively final

For the result variable. I have seen Java: Assign a variable within lambda with a similar problem but there the problem involved String and the solution was to set it to null beforehand.

I feel I'm close. How can I fix this?

like image 904
cs95 Avatar asked Oct 20 '25 10:10

cs95


1 Answers

The problem is that result is not effectively final as there are more than one assignments to it.

You can use Optional.map

private boolean isNullOrEmpty(Optional<String> value) {
  return value.map(v -> isEmptyOrWhitespace(v)) //Or can use a Method reference as mentioned by Bohemian@
        .orElse(false);
} 
like image 190
user7 Avatar answered Oct 22 '25 00:10

user7



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!