error: incompatible types: unexpected return value : Java 8

  • A+
Category:Languages

I have written a simple method which returns the boolean value.

private boolean isActionAvailable(Collection<StudentConfiguration> studentConfigs){        if(studentConfigs != null)         {             studentConfigs.forEach(studentConfig -> {                 if(studentConfig.action() == null || !studentConfig.action().equals(Action.DELETE)) {                     return true;                 }             });         }         return false;     } 

The method is throwing the following exception .

error: incompatible types: unexpected return value             studentConfigs.forEach(studentConfig ->  

What's the problem with my code?

 


The lambda expression passed to forEach shouldn't have a return value.

It looks like you want to return true if any of the elements of the input Collection satisfies a condition:

private boolean isActionAvailable(Collection<StudentConfiguration> studentConfigs){     if(studentConfigs != null) {         if (studentConfigs.stream().anyMatch(sc -> sc.action() == null || !sc.action().equals(Action.DELETE))) {             return true;         }     }     return false; } 

As Holger suggested, this can be reduced to a single statement:

return studentConfigs != null && studentConfigs.stream().anyMatch(sc -> sc.action() == null || !sc.action().equals(Action.DELETE)); 

or

return studentConfigs != null ? studentConfigs.stream().anyMatch(sc -> sc.action() == null || !sc.action().equals(Action.DELETE)) : false; 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: