Search code examples
javatype-inferencetype-safety

How does this function not break Java type safety requirements?


I was trying to figure out how some of the getParcelable() type functions in Android work and I was able to bundle my misunderstanding into this short snippet:

<T> T someFunction() {
    Object a = new Object();
    return (T)a;
}

void testSomeFunction() {
    String a = someFunction();
    List<Activity> activityLIst = someFunction();
    int[] intArray = someFunction();
}

Why does the compiler allow this? To me this appears to break type safety without the code calling the function ever having to cast the return value. Is seems like you could technically replace every single non 'void' return parameter with

<T> T 

and it would compile fine (and run fine if you got it all right). Does anyone have any information on the peculiar format of the return parameter?


Solution

  • Of course it breaks type safety, and all of the common Java compilers will at least output a warning on the cast (T) a. Generally, though, the compiler can't always trace back to the creation of the object stored in a to prove it's really of the wrong type, so the compiler won't actually forbid this.