Close

Generalized Target-Type Inference

[Last Updated: Feb 10, 2016]

Java 7 introduced diamond operator <>. The compiler can infer parameter types for constructors of generic classes. for example:

List<String> list = new ArrayList<>();

Java 8 improves type inference at one more place, i.e. when targeting method parameters with specific generic data type.

Example

Let's say we have a class Amount as given by:

public class Amount<T> {
}

Now we want to call a method twice( ... ) and pass a new instance of Amount, targeting a specific data type i.e Integer for 'T'. In Java 7 the code will look like this:

 public static void main(String[] args) {
        twice(new Amount<Integer>());
    }

    public static void twice(Amount<Integer> amount) {
        //todo: apply twice logic
    }

Java 8 added support for method type-parameter inference in method context, so we can now remove the specific generic type when calling twice. Now our code will look like this:

 public static void main(String[] args) {
        twice(new Amount<>());//In Java 8 we don't need specific target data type.
    }

    public static void twice(Amount<Integer> amount) {
        //todo: apply twice logic
    }

The above code would be a compile time error in Java 7:

Error:(9, 15) java: incompatible types: com.logicbig.example.Amount<java.lang.Object> cannot be converted to com.logicbig.example.Amount<java.lang.Integer>

Example Project

Dependencies and Technologies Used:

  • JDK 1.8
  • Maven 3.0.4

Target Type Inference Select All Download
  • target-type-inference
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • InferTargetTypeExample.java

    See Also