Questions tagged [covariance]

Covariance, contravariance and invariance describe how the existing type inheritance hierarchy changes when subjected to some transformation (such as usage within generics). If the transformation keeps the ordering of the original hierarchy, it is "covariant". If it reverses it, it is "contravariant". If it breaks it, it is "invariant".

About Type Ordering

Let's say that a class P (parent) is inherited by a class C (child).

We can denote this fact as: P > C.

Informally, P is "larger" than C since it "contains" all the possible instances of C, but can also contain some other instances that are not C. Child is always parent but not necessarily the other way around.

Variance in Generics

Let's say that there is a generic type G that has a single generic parameter T, denoted by: G{T}.

  • If G{P} > G{C}, then T is co-variant (it preserves the original inheritance ordering).
  • If G{P} < G{C}, then T is contra-variant (it reverses the original inheritance ordering).
  • If G{P} and G{C} are type-unrelated, then T is invariant (it "breaks" the inheritance).

So the variance is the property of transformation (in this case: generic parameter T of G), not the original type hierarchy (P and C).

C# Examples

The generic parameter T of IEnumerable<out T> is covariant (as denoted by "out" keyword), meaning you can "forget" that the collection contains Cs and just treat it as if it contains Ps. For example:

IEnumerable<C> ec = ...;
IEnumerable<P> ep = ec;

The generic parameter T of Action<in T> is contravariant (as denoted by "in" keyword), meaning that an action that accepts P can also accept C. For example:

Action<P> ap = ...;
Action<C> ac = ap;

The generic parameter T is contravariant and generic parameter TResult is covariant in Func<in T, out TResult>. Each generic parameter is considered a different "transformation" with its own variance. This lets you write a code like this:

Func<P, C> fpc = ...;
Func<C, P> fcp = fpc;

And finally, the generic parameter T of IList<T> is considered invariant, so IList<P> and IList<C> are considered unrelated types (there is no assignment compatibility in either direction).


Tag usage

  • Do not use for the measurement of the strength and direction of the linear relationship between two random variables (statistical context). Instead, use other related tags, for example, .
    Moreover, consider whether the question might be better suited to Cross Validated, the Stack Exchange site for statistics, machine learning and data analysis.
1905 questions
0
votes
0 answers

How to I calculate conditional variance Var(Y2|Y1) in R

I am sure this must not be difficult but for the life of me, I can't find a function in R to do this. All help appreciated.
ingrid
  • 47
  • 1
  • 7
0
votes
0 answers

Plotting the off-diagonal value of a covariance matrix

This block of code outputs all 10 of my covariance matrices and plots every point in the 2x2 matrix. for i in range(10): columns = datawithoutmean[:, i*2:i*2 + 2] cov = numpy.cov(columns.T) print(cov) …
0
votes
1 answer

Mixing contravariant and covariant types in Scala

I am trying to build a framework with a hierarchy of Contexts (that hold immutable data) and Modules that create actors work with the data. Subclasses on Context include more data (e.g., a RemoteContext would have information about how to…
0
votes
0 answers

Question on covariance and contravariance

I have read in so many blogs that a method's inputs are contravariant and return type is covariant. As for as I understand, both are covariant (where in place of actual type, it's subtype can be given). This can be demonstrated with the below…
user3103957
  • 636
  • 4
  • 16
0
votes
1 answer

How to calculate covariance on 2 columns out of multiple columns in python?

I've provided a sample data below. It contains 8x10 matrix which contains two-dimensional normal distribution. For ex, col1 and col2 is 1 set, col3/col4 is another and so on. I'm trying to calculate covariance of the individual set in python. So…
trollKing
  • 3
  • 2
0
votes
1 answer

What is the difference between Source[T, _] and Source[T, NotUsed]?

I have an application which is built on top of the Play/Lagom stack. I need to call a service which requires Source[T, NotUsed] to stream a file to it. This is the interface of the service: def foo(fooId: UUID): ServiceCall[Source[ByteString,…
arnaudoff
  • 686
  • 8
  • 20
0
votes
1 answer

Conversion not possible in dotnet core with inheritance and generics

Here is my current code (.net core): Box code: class Box { } SpeicalBox code: class SpecialBox : Box { } Stack code: interface Stack where T : Box { AnotherInterface TheFunction(); } SpecialStack code: class SpecialStack :…
Tobias Etter
  • 744
  • 1
  • 6
  • 19
0
votes
0 answers

How do I obtain a good error value when propagating it from a fit?

I am fitting some data I have with a function. With the fitted function I want to see where it crosses some threshold value, determine this threshold value and get an error on this value as well. When using the curve_fit toolbox with the…
0
votes
1 answer

Scala type variance

I have the following code class Person class Warrior extends Person trait Commander[A] { def giveOrder(to: A) def delegate(to: Commander[A]) } val warCommander: Commander[Warrior] = new Commander[Warrior] { override def giveOrder(to:…
gurghet
  • 7,591
  • 4
  • 36
  • 63
0
votes
3 answers

Generic method with variance in C#?

Consider following classes (inheritance tree): public class A {} public class B: A {} And this method: public IList MyMethod(){ IList result = new List(); //add some items to result return result; } The compiler is unhappy.…
Rasto
  • 17,204
  • 47
  • 154
  • 245
0
votes
2 answers

How to return wildcard generic?

I have a type alias with parameter and I would like to return the instance of different parameter types from a method: type TC[T] = (ClassTag[T], Option[T]) def gen(x: Int): TC[_] = x match { case 0 => (classTag[Int], Option[Int](0)) case _ =>…
SwiftMango
  • 15,092
  • 13
  • 71
  • 136
0
votes
1 answer

How to pass extential type of tuple to invariant generic function?

I have an extential type of tuple, and I want to pass it to a generic function (I use ClassTag in this example but it is a custom type class with invariant type parameter): type TC = (ClassTag[T], Option[T]) forSome {type T} def foo[T](ct:…
SwiftMango
  • 15,092
  • 13
  • 71
  • 136
0
votes
1 answer

Why does mutability preclude covariance?

I'm trying to understand how covariance works (in general, though my examples will be in C#) and what governs when a generic type can be covariant. Assume we have a class Animal with subclasses Cat and Dog. I get why a read-only type such as…
DylanSp
  • 1,379
  • 13
  • 27
0
votes
1 answer

Why does Scala function allow subclass parameter when specifyied super class parameter

<: seems to work like I'd expect, however, >: does not. object TheCakeIsALie extends App { class Food class Junk extends Food class Cake extends Junk val food = new Food val junk = new Junk val cake = new Cake def subJunk[T <:…
dwarfer88
  • 115
  • 1
  • 6
0
votes
1 answer

What is the calculation process for np.cov() in Python?

I am learning Mahalonobis Distance by following: https://www.machinelearningplus.com/statistics/mahalanobis-distance/ I kind of confused by the concept of the covariance matrix of arrays, assume we have a data frame like this: comedy …
Cecilia
  • 309
  • 2
  • 12
1 2 3
99
100