Home > Software engineering >  Type Inference Algorithm
Type Inference Algorithm

Time:07-28

Why inference determines that the second argument being passed to the pick method is of type Serializable ? Why s compiles but s1 line doesnt compile

static <T> T pick(T a1, T a2) { return a2; }
Serializable s = pick("d", new ArrayList<String>()); //this works
String s1= pick("d", new ArrayList<String>());//doesnt compile

CodePudding user response:

Because the result and both arguments must be the same type - the T.

In the second example, the result is a String, first parameter is a String, but the second argument is an ArrayList. String != ArrayList

In the first example, the first argument is a String (and the String implements Serializable interface), the second argument is an ArrayList, but List implements the Serializable. So the result can be Serializable too - it is a something common to all there 3 objects.

CodePudding user response:

For every invocation of the method, pick() type T needs to be inferred by the compiler.

Both calls of the pick() in your code snippet are so-called poly expressions (i.e. sensitive to the context), because they appear in the assignment context. Hence, target type in both cases would be inferred from the assignment context :

  • in the first case, target type is Serializable and compiler successfully performs widening convection of both arguments (String and ArrayList<String>) to Serializable, because it's a supertype of both;

  • in the second case, target type for type parameter T is String and compiler issues a compilation error because it fails to convert the second argument of ArrayList<String> to String, these types are unrelated.

  •  Tags:  
  • java
  • Related