I have following problem, I'm not sure if it is IntelliJ Bug or something else.
I have static function which maps string to boolean. When I use this function in Optional.map()
it maps every time to Boolean instead of boolean. Is this standard behavior of type inference?
public class MyClass {
public void myMethod() {
Optional<String> myAttribute = Optional.of("1");
final var myBoolean = myAttribute
.map(MyClass::mapStringToBoolean) //it maps to Optional<Boolean>, why not to boolean when function gives primitive back?
.orElse(false);
// "myBoolean" is Boolean instead of boolean
}
public static boolean mapStringToBoolean(String myString) {
return "1".equals(myString) || "true".equals(myString);
}
}
CodePudding user response:
Optional<T>#orElse
returns T
, which cannot be a primitive. Try replacing var
with boolean
to force unboxing.
CodePudding user response:
Primitives cannot be used as generics in Java so you are getting autoboxed. Try to declare eg List<int>
to see what will happen.