Why is the compiler able to determine the generic type parameter for an
assignment, but not for the ternary operator (?
)?
I have a question regarding the compiler being able to deduce the generic type
parameter in case of a "direct" assignment but failing in case of the ternary
operator (?
). My examples uses Guava's Optional
class, to make my point, but
I think the underlying issue is generic and not restricted to Optional
.
Optional
has a generic function absent()
:
public static <T> Optional<T> absent();
and I can assign an Optional<T>
to an Optional<Double>
:
// no compiler error
final Optional<Double> o1 = Optional.absent();
How does the compiler realize, that T
should be Double
in this case. Because
when using the ternary operator (?
), I need to tell the compiler specifically
to us Integer
as the generic parameter
// Type mismatch: cannot convert from Optional<capture#1-of ? extends Object> to Optional<Integer>
final Optional<Integer> o2 = true
? Optional.of(42)
: Optional.<Integer>absent();
otherwise I get the following error
Type mismatch: cannot convert from
Optional<capture#1-of ? extends Object>
toOptional<Integer>
Why is there a difference between a "direct" assignement and using the ternary operator? Or is there something else I am missing?