Why can’t type conversion be done directly in Java?
In the following code fragment, why are lines 1 and 2 not problematic and line 3 causing a compilation error? Are the first two lines functionally not equivalent to the third line?
Loader loader = getLoaderManager().getLoader(0);
PatientLoader patientLoader = (PatientLoader) loader;
patientLoader = (PatientLoader) getLoaderManager().getLoader(0); // ERROR!
Throw this:
java: somepath/Patient.java:99: inconvertible types
found : android.content.Loader<java.lang.Object>
required: com.example.package.PatientLoader
PatientLoader
Indirect extensionsLoader<>
.
I have a C# background and in C# this is not a problem, so I may have missed some information about the Java type system.
PatientLoader
AsyncTaskLoader<Cursor>
Anyone familiar with the Android SDK will know AsyncTaskLoader<>
about extensionsLoader<>
.
Solution
Regardless of the position of the parentheses.
This issue is related to generics:
For example, compilation failed:
Loader<Object> loader = getLoaderManager().getLoader(0);
PatientLoader ch = (PatientLoader)loader; // Will show compile error (Cannot cast from Loader<Object> to PatienLoader)
But this will compile fine:
Loader<?> loader = getLoaderManager().getLoader(0);
PatientLoader ch = (PatientLoader)loader; // Compiles fine.
The difference is between generic
The problem is that getLoader(int) is defined as returning a Loader
PatientLoader ch = (PatientLoader)getLoaderManager().getLoader(0); // Compile error.
I think this is a “bug” in the SDK. The getLoader(int) method should be defined to return a Loader> not a Loader