I have a function that returns a type of generic class K
which extends the Comparable
interface. This function calls itself recursively. Interestingly, when it gets called I receive the error Type mismatch: cannot convert from Comparable to K.
public class NonEmptyTree<K extends Comparable<K>, V> implements Tree<K, V> {
Tree right;
K key;
...
public K max() throws EmptyTreeException {
try {
return right.max(); // "Type mismatch: cannot convert from Comparable to K"
} catch (EmptyTreeException e) {
return key;
}
}
...
}
Changing the return statement to return (K) right.max();
removes the error and produces the expected behavior.
Why is the cast necessary and how can I produce the code such that does not require casting?
key
of typeK
?<K extends Comparable<? super K>>
b) where / how isright
defined?key
is of typeK
. @zaplright
is of typeTree
, which the class extends.Tree
orTree<K, V>
? Ah I see your edit now. The problem is, that you use the raw type ofTree
. Change it to match the generic type.