I'm using Java 1.8.0_151 and there is some code that doesn't compile and I don't understand:
Optional optional = Optional.of("dummy");
Optional<Boolean> result1 = optional.map(obj -> true); // works fine
boolean result2 = result1.orElse(false); // works fine
boolean result3 = optional.map(obj -> true).orElse(false); // compilation error: Incompatible types: required boolean, found object
Object result4 = optional.map(obj -> true).orElse(false); // works fine
why it works fine on result1
but gives compilation error on result3
?
Additional info:
- In the first line, when I change
Optional
toOptional<String>
, result3 is also able to compile - When I break
result3
into 2 lines: likeresult1
andresult2
,result3
is able to compile