Skip to content

Commit c543fb7

Browse files
add usage
1 parent ae6a28f commit c543fb7

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

README.md

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,42 @@ This is a project that incorporates Java annotations in order to allow specifica
3535
$ git submodule add https://github.com/bldl/java-variance
3636
```
3737

38-
## Usage
38+
## What is variance
39+
40+
# Variance in Generic Programming
41+
42+
**Variance** in Generic Programming refers to how subtyping between more complex generic types (like `List<T>`) relates to subtyping between their type parameters (like `T`). It determines whether type relationships are preserved, reversed, or invariant when generic types are involved.
43+
44+
## Types of Variance
45+
46+
### 1. **Covariance**
47+
48+
Covariance allows a generic type to be substituted with another generic type that has a more specific (derived) type parameter.
49+
50+
- Example: `List<Animal>` can accept `List<Dog>` if `Dog` is a subtype of `Animal`.
51+
- Used when a generic type is only **producing** (out) values.
52+
- Marked with **`out`** in Kotlin or achieved with `? extends` in Java.
53+
54+
### 2. **Contravariance**
55+
56+
Contravariance allows a generic type to be substituted with another generic type that has a more general (base) type parameter.
57+
58+
- Example: `List<Dog>` can accept `List<Animal>` if `Animal` is a supertype of `Dog`.
59+
- Used when a generic type is only **consuming** (in) values.
60+
- Marked with **`in`** in Kotlin or achieved with `? super` in Java.
61+
62+
### 3. **Invariance**
63+
64+
Invariance means no substitution is allowed between different generic types, even if their type parameters have a subtype relationship.
65+
66+
- Example: `List<Animal>` and `List<Dog>` are entirely distinct and incompatible.
67+
- This is the default in many languages, like Java's generics.
68+
69+
---
70+
71+
## Key Insight
72+
73+
Covariance and contravariance depend on how the generic type uses its type parameter: **producing outputs** (covariance) or **consuming inputs** (contravariance). Invariant types neither allow flexibility.
3974

4075
### Annotations
4176

0 commit comments

Comments
 (0)