> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Kotlin Contravariance

Contravariance is a generic type system feature that reverses the standard subtyping relationship between parameterized types. In Kotlin, if type `Sub` is a subtype of type `Super`, a contravariant generic type `Generic<T>` establishes that `Generic<Super>` is a subtype of `Generic<Sub>`. This allows a generic instance typed to a superclass to be safely assigned to a reference typed to a subclass.

Kotlin implements contravariance using the `in` variance annotation. This modifier restricts the generic type parameter so that it can only be consumed (passed as input arguments to functions) and never produced (returned from functions or exposed as public properties).

## Declaration-Site Variance

When the `in` modifier is applied at the class or interface declaration, it is known as declaration-site variance. The Kotlin compiler enforces the "in-position" restriction across the entire type.

```kotlin theme={"dark"}
interface Consumer<in T> {
    // Valid: T is in an input position
    fun consume(item: T) 
    
    // Compilation Error: Type parameter T is declared as 'in'
    // and cannot occur in an 'out' position.
    // fun produce(): T 
}
```

## Subtyping Mechanics

The reversal of the subtyping relationship is the core mechanic of contravariance. Because a `Consumer<Super>` can handle any instance of `Super`, it is logically safe to treat it as a `Consumer<Sub>`, since `Sub` is guaranteed to possess all the traits of `Super`.

```kotlin theme={"dark"}
open class Animal
class Dog : Animal()
class Cat : Animal()

interface Handler<in T> {
    fun handle(item: T)
}

// Instantiate a handler for the supertype
val animalHandler: Handler<Animal> = object : Handler<Animal> {
    override fun handle(item: Animal) {
        println(item)
    }
}

// Valid: Handler<Animal> is a subtype of Handler<Dog>
val dogHandler: Handler<Dog> = animalHandler

// The underlying animalHandler safely consumes a Dog, 
// because a Dog is an Animal.
dogHandler.handle(Dog()) 
```

## Type Safety Enforcement

The compiler strictly enforces the `in` restriction to prevent runtime `ClassCastException`s. If a contravariant type were permitted to return `T`, type safety would collapse.

If `Handler<in T>` allowed a function `fun get(): T`, the following invalid state would compile:

1. `animalHandler` is assigned to `dogHandler`.
2. `animalHandler.get()` internally returns a `Cat` (which is valid for `Handler<Animal>`).
3. `dogHandler.get()` expects a `Dog`, but receives the `Cat` from the underlying `animalHandler`.

By restricting `T` to input positions, the compiler guarantees that the generic type only ever receives data it is equipped to handle, and never promises to return data of a specific subclass.

## Use-Site Variance (Type Projections)

If a generic class is invariant (declared without `in` or `out`), contravariance can be applied at the point of usage. This is called a type projection. It restricts the API of the invariant class for that specific reference, hiding any methods where `T` appears in an `out` position.

```kotlin theme={"dark"}
// Invariant class
class Box<T>(var item: T) 

// Use-site contravariance
fun putString(box: Box<in String>, value: String) {
    // Valid: We can write to the box because String is expected
    box.item = value 
    
    // Compilation Error: Type mismatch. 
    // The compiler only knows the item is Any?, not String.
    // val retrieved: String = box.item 
}

val anyBox = Box<Any>("Initial")
// Valid: Box<Any> is projected as Box<in String>
putString(anyBox, "New String") 
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Kotlin Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
