Type Inference from Arguments

Java-Type Inference from Arguments

Type Inference from Arguments

Generally generic method infer its type from its argument. For example , in the following generic method showAndGetV( ) calls look like normal method calls.

Type Inference from Arguments

But what if there is more than one argument? For example, following generic method showAndGetV( ) contain two arguments :

Type Inference from Arguments

All looks well when we give it two identical types. For example :

Type Inference from Arguments

But what does it make of the different type of arguments ?  For example :

Type Inference from Arguments

In this case, the Java compiler does something really smart. It climbs up the argument type parent classes, looking for the nearest common supertype. Java also identifies the nearest common interfaces implemented by both of the types. It identifies that both the Integer and the Float types are subtypes of the Number type. It also recognizes that each of these implements (a certain generic instantiation of) the Comparable interface. Java then effectively makes this combination of types the parameter type of V for this method invocation. The resulting type is, to use the syntax of bounds, Number & Comparable. What this means to us is that the result type V is assignable to anything matching that particular combination of types.

Type Inference from Arguments

The last two statements says that we can work with our Integer and our Float at the same time only if we think of them as Numbers or Comparables, which makes sense. The return type has become a new type, which is effectively a Number or Comparable . This same inference logic works with any number of arguments. But to be useful, the arguments really have to share some important common supertype or interface. If they don’t have anything in common, the result will be their de facto common supertype, the Object type. For example, the nearest common supertype of a String and a Integer is Object along with the Comparable interface. There’s not much a method could do with a type lacking real bounds anyway.

Program

Type Inference from Arguments

Program Source

public class Javaapp {
    
    static <V> V showAndGetV(V v1,V v2) {

        System.out.println("v1 : " + v1.getClass().getName());
        System.out.println("v2 : " + v2.getClass().getName());
        return v1;
    }
    
    public static void main(String[] args) {
        
         Number n = showAndGetV(200,15.5f);
         Comparable c = showAndGetV(200,15.5f);
    }
}

Leave a Comment