# Generics, variance problems and bounded types

In scala, generics work for both classes and traits. We can have any number of generic type arguments.

```class MyList[A] {
def add(element: A): MyList[A] = ???
}
val listOfIntegers = new MyList[Int]
val listOfStrings = new MyList[String]
```

// we can have any number of generic type arguments
class MyMap[K, V]

Variance
It defines inheritance relationships of parameterized types. There are 3 types of variance

```class Animal
class Cat extends Animal
class Dog extends Animal
```

Covariance: List[Cat] can extend from List[Animal]

```    class CovariantList[+A] // Observe the symbol +
val animal: Animal = new Cat
val animalList: CovariantList[Animal] = new CovariantList[Cat]
```

Invariance: List[Cat] cannot extend from List[Animal]

```  class InvarianceList[A]
val invariantAnimalList: InvarianceList[Animal] = new InvarianceList[Animal]
```

Contravariance: List[Animal] can extend from List[Cat]

```    class ContraVariantList[-A]
val contraVariantList: ContraVariantList[Cat] = new ContraVariantList[Animal]
// this may be confusing, look at the below example
class Trainer[-A]
val contraVariantList1: Trainer[Cat] = new Trainer[Animal]
// Now this makes sense as animal trainer can also train cat
```

Bounded Types
These allow us to use generic classes only for certain types either subtype/supertype of certain types

```SubType
class Cage[A <: Animal](animal: A) // it says class Cage accepts
// only of type A that are sub type of Animal
val cage = new Cage(new Dog)
class Car
// val newCage = new Cage(new Car) // compiler does not
SuperType
// this enforces super type
class Cage1[A >: Animal](animal: A)
```

Mawazo

Mostly technology with occasional sprinkling of other random thoughts

amintabar

Amir Amintabar's personal page

101 Books

Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)

Seek, Plunnge and more...

My words, my world...

ARRM Foundation

Do not wait for leaders; do it alone, person to person - Mother Teresa

Executive Management

An unexamined life is not worth living – Socrates

javaproffesionals

A topnotch WordPress.com site

thehandwritinganalyst

Just another WordPress.com site

coding algorithms

"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey