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
1 answer

Passing an interface to another interface method

I need to implement an event-listener model in OOP. Now I have EventInterface and ListenerInterface. But I want to pass the event to a listener, as: interface ListenerInterface { public function listen(EventInterface $event); } But I can't do…
Alexxosipov
  • 1,215
  • 4
  • 19
  • 45
0
votes
1 answer

C# covariant/contravariant types utilizing generics with Dictionary

i need to help with solving Covariant situation in my Code. Let me show the situation on example: abstract class BaseSource { } abstract class BaseTarget { } class SourceEntityA : BaseSource { } class TargetEntityB : BaseTarget { } interface…
Glock
  • 63
  • 4
0
votes
0 answers

Alternatives to covariant HashMap in Scala

I need a map-like mutable data structure in Scala that is covariant in it's value type parameter. This is impossible to implement in Scala because mutable data structures are invariant in their type parameters. I understand the rationale for that…
eager2learn
  • 1,447
  • 4
  • 24
  • 47
0
votes
1 answer

Question about covariant parameters in Java

I have this piece of code: class X { int x = 1; } class Y extends X { int y = 2; } class Z extends Y { int z = 3; } class A { public Y metodo1(Y y) { System.out.println("Metodo1 de A"); return new Y(); } …
Awacate
  • 125
  • 2
  • 10
0
votes
1 answer

Sample covariance matrix far from truth even for large sample size with 2D gaussian

Here is a very simple script generating a 2D gaussian with 10000 points. The covariance matrix estimated by np.cov seems really far from the generating one. What is the explanation and are there solutions ? import numpy as np import…
Jo37
  • 45
  • 1
  • 5
0
votes
0 answers

Kotlin: storing and invoking functions with type parameter in generic collections

I am writing simple expert system in Kotlin. Let's start with the facts. I implemented Fact as follows: data class Fact(val id: String, val value: T) To give an example, it's instance would look like this: val f1 = Fact("adult", true)…
PGliw
  • 311
  • 4
  • 9
0
votes
1 answer

LDA covariance matrix not match calculated covariance matrix

I'm looking to better understand the covariance_ attribute returned by scikit-learn's LDA object. I'm sure I'm missing something, but I expect it to be the covariance matrix associated with the input data. However, when I compare .covariance_…
0
votes
3 answers

Contravariance/Covariance - cannot convert class to interface

I have the following code public interface IInterface { } public class GenericClass where TSomeClass : class { public TSomeClass SomeMethod(TSomeClass someClass = null) { return SomeClass.SomeClassStaticInstance; …
0
votes
1 answer

scala type system - understanding covariant with lower/upper bounds

I am new to scala and have questions on scala generics Question is how animalContainer.add method is accepting new Cat. From my understanding B>:A - A is Animal and B is Cat. Cat is NOT super typs of animal . How it is working..
Learn Hadoop
  • 2,760
  • 8
  • 28
  • 60
0
votes
1 answer

How to calculate Covariance for a population not sample in pandas?

pandas is using "Sample Concept" where divisor is (N-1) as stated here cov method while I need to calculate it for a population so divisor is (N) not (N-1). How could I do this? Currently, I multiply output by (N-1)/(N) Sample vs Population Formula
Maged
  • 818
  • 1
  • 8
  • 17
0
votes
0 answers

Trouble computing covariance and variance

I want to compute the covariance and the variance of two times series but for some reason, I always get a "NA" answer. My data seems to be fine, they are real numbers without special features. The code looks like this: > a = cov(dtarussell, dtasp) >…
0
votes
0 answers

Linear Discriminant Analysis(LDA) - Covariance matrix issue

I am trying to follow this you this video LDA example : LDA video example from Youtube On 7th minute if video formula to calculate co-variance matrix is given , and direct output of co-variance matrix is given as without explaining the mathematical…
user8588795
  • 321
  • 2
  • 14
0
votes
5 answers

Return more inherited Generic class from method?

I have such interface: public interface IImportModel { } And class which implements this interface: public class MaterialImportModel: IImportModel { public string Name { get; set; } } Also I have interface for processors of import: public…
Vlad B
  • 1
  • 3
0
votes
0 answers

3D covariance matrix - vectrorizing python

I need to speed up a python code, I would like to avoid the use of the following for cycle, where "data" matrix has dimension [dim1xdim2]: for i in range(int(dim1)): data_process = data[i,:].reshape((dim2, 1)) rxx = data_process *…
Luca R
  • 1
  • 2
0
votes
1 answer

Referencing a derived type inside itself

I have something link this: public abstract class Wrapper: where TWrapped : Wrapper { protected T baseObject; protected ICollection baseList; protected ICollection wrappedList; public Wrapper (T…
Luiz Borges
  • 537
  • 1
  • 5
  • 19