Redundant generic parameters

后端 未结 6 1867
没有蜡笔的小新
没有蜡笔的小新 2021-01-12 03:36

I have this two interfaces and classes:

public interface Identifiable {
    T getId();
}

public interface GenericRepository

        
6条回答
  •  隐瞒了意图╮
    2021-01-12 04:17

    It's not redundant from the standpoint of the GenericRepository class. When it has methods like T get(K id), it can't know which types of the id argument it can accept otherwise. You can write the following:

    interface GenericRepository> {
        T get(Object id);
    }
    

    Now you don't have to write Long as a type parameter, but you lose the possibility to check if the get method is used properly at compile time. So the type variable serves a specific purpose.

    And as for the field declaration, when you have a generic type, you have to specify all the type variables it uses. Of course, you could argue that it would be neat if the language could understand that one of the parameter values can be inferred from the other one, but it is debatable.

提交回复
热议问题