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:

JavaScript

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:

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