The CLR does not support covariant return types or full variance (i. e. applied to classes, not only interfaces and delegates), but there are languages targeting the CLR which use one or both of these features.
Is there some practical workaround for the CLR to enable this functionality or do these languages employ some kind of rewriting/erasure/... technique to fully support their feature set?
Covariant return type works only for non-primitive return types. From Java 5 onwards, we can override a method by changing its return type only by abiding the condition that return type is a subclass of that of overridden method return type. Following example showcases the same.
Covariance allows assigning an instance to a variable whose type is one of the instance's generic type; i.e. supertype. Contravariance allows assigning an instance to a variable whose type is one of the instance's derived type; i.e. subtype.
In object-oriented programming, a covariant return type of a method is one that can be replaced by a "narrower" type when the method is overridden in a subclass. A notable language in which this is a fairly common paradigm is C++.
The covariant return type A primitive type like int , float , reference , or void type can be the return value. As we said earlier, covariant return type means that a method's return type can be replaced with a narrower one when overridden in a subclass or child class.
Probably the same way that Java does it (Java 5 supports covariant returns at the language level, but the JVM doesn't support it): by adding synthetic methods. Here's how Java does it: say you have a class like this:
class Foo implements Cloneable {
@Override
public Foo clone() {
// ...
}
}
Behind the scenes, two clone
methods get generated: public Foo clone()
(which contains the real code), and public Object clone()
(which simply returns the result of the former). The latter method (which is synthesised) is how the clone
method gets to be overridden at the JVM level.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With