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 incompatible types error most often occurs when manual or explicit conversion between types is required, but it can also happen by accident when using an incorrect API, usually involving the use of an incorrect reference type or the invocation of an incorrect method with an identical or similar name.
This is not a Java syntax error. (@StackOverflow) There really isn’t an easy fix when the compiler gives an “incompatible types” message: There are functions that can convert types. Developer may need to change what the code is expected to do.
You’ll get the “missing return value” message when the return statement includes an incorrect type. For example, the following code: Usually, there is a return statement that doesn’t return anything. Read this discussion about how to avoid the “missing return value” Java software error message. (@coderanch)
This Java software error message means the return type of a method was not explicitly stated in the method signature. There are a few ways to trigger the “invalid method declaration; return type required” error: If the method does not return a value then “void” needs to be stated as the type in the method signature.
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;
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