Although the conditional operator is not exactly same as if-else
conditional, but this is a different issue.
This is a known bug with type inference of generic type parameter with conditional operator which doesn't work as expected.
The solution is to provide explicit type argument:
K k1 = (1==1) ? null : this.<K>createK();
...this would work, however with compiler warning - Dead Code (of course, due to 1 == 1
part). Note, how we need to explicit use this
to invoke the method with explicit type argument. Simply doing <K>createK()
won't work.
Adding the explicit type argument with method invocation - this.<K>createK();
forces the type T
to be inferred as K
, which is otherwise inferred as Object
.
However, I suspect that your doubt is really related to the type inference. It's just a coincidence that the issue came out to be that. Even though, to get some idea about how conditional operators work in different situations, and what the type of its result is, you can schedule a visit to JLS §15.25 - Conditional Operator