Skip to content
Advertisement

Does it matter if function returns T or object if T can not be inferred from context?

I found the following source code in gson:

public <T> T fromJson(Reader json, Type typeOfT) throws JsonIOException, JsonSyntaxException
{
    JsonReader jsonReader = newJsonReader(json);
    T object = (T) fromJson(jsonReader, typeOfT);
    assertFullConsumption(object, jsonReader);
    return object;
}

Does it matter if fromJson function declares to return an Object or return T? at least from my knowledge, if the T can not be inferred by function arguments it acts exactly as object. So why the source code uses T instead of an Object?

Advertisement

Answer

This doesn’t return Object but a type that’s either inferred from the context or – if that’s not possible – by passing a type parameter with a type witness: YourClass.<String>fromJson()

Note that this won’t magically work. If the object that’s returned from the internal call isn’t compatible with T at runtime, the assignment (of the outer return value) will throw a ClassCastException.

Example:

public class MyClass {
    public static void main(String args[]) {
        String result1 = MyClass.test(); // works as expected
        Object result2 = MyClass.<Integer>test(); // works "surprisingly"
        int result3 = MyClass.test(); // cannot be cast to java.lang.Integer
    }
    
    static <T> T test() {
        try {
            return (T) "Hello World";
        } catch (ClassCastException e) {
            throw new Error(); // never reached
        }
    }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement