recently I've stumbled upon an edge case with generics that doesn't seem logical.
I've got a simple interface that returns a list of children:
public interface INode<C extends INode> {
List<C> getChildren();
}
I would expect that if the INode type is referenced without defining the C type, the C type would be inferred by a compiler as the INode. In other words, in below code:
public void retrieveChildren(INode node) {
var children = node.getChildren();
}
children would be inferred as of List<INode> type. Instead, it's just plain List.
Worth noting that type inference works as expected with the INode method returning a single element, so when this interface:
public interface INode<C extends INode> {
C getFirstChild();
}
is used in the following method:
public void retrieveFirstChild(INode node) {
var firstChild = node.getFirstChild();
}
firstChild is propely inferred as INode.
Is there a rationale for the jdk to work like that? Also, is there a clean way to enforce a C type for a returned list?
Many thanks.