Type Witness in java generics

Some quick answers to your questions:

What is the right way to do this? Using Type Witness or let Java infer?

There is no technical correct answer for this as both approaches are valid. But code readability should always be the quality criterion. So the latter is better. Additionally you might change the type of your arguments at a later point in development. With type inference you do not have to change that line.


Is there a case where using type witness is absolutely needed?

Yes. It is needed when type cannot be inferred from the input arguments to a method. Maybe the generic type is only used for the return value, independently from the types of the arguments. Then you simply must specify it.


Is this a feature from Java 5 or added later?

Generics are a language feature from Java 5 on. Type inference is a compiler feature that is specified in the Java Language Specification (JLS). In the Java 8 JLS this topic got an own chapter. Each Java version did some enhancements in that feature. For example Java 7 introduced the diamond operator. Type witness for methods was already introduced in Java 5 as far as I know.

Leave a Comment