Skip to content
Advertisement

Type Inference Algorithm

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement