Kotlin generics
kotlin generics variance
Similar to what Java provisions, kotlin support generics and also variance, but is easier to understand and use.
For instance we have a class Container
that accepts T
is type parameter.
1 |
|
The class Container
itself can have inheritance and everything, but when creating instance, it is not the case.
1 |
|
Would result into error below:
Type mismatch.
Required: Container
Found: Container
This is because Container<Any>
is not
the parent class of Container<String>
.
But in reality, there are many situations that we would want our class to behave as a generic container to deal with certain types and its inheritance, there comes the variance
conception.
in
This is to denote the generic type can only be used as input parameter, but can never return.
1 |
|
Here the class Container
is used as consumer
of type T
, thus any type that extends T can be passed as function parameter, but never as return value.
out
1 |
|
This time, Container
class is used as producer
, it may return any super class of T, hence the return value can be assigned to the variable b
and c
.