Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do languages Scala which need covariant return types and "real" class variance run on the CLR?

Tags:

c#

types

clr

c#-2.0

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?

like image 718
soc Avatar asked Jul 19 '11 21:07

soc


People also ask

How is covariant return types implemented?

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.

What is covariance and Contravariance in Scala?

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.

What do you understand by covariant return type?

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++.

What is a covariant return type void?

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.


1 Answers

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.

like image 100
Chris Jester-Young Avatar answered Nov 15 '22 22:11

Chris Jester-Young