There is a sealed-class Result, which is parameterized with two types - success result (T) and error type (R).
It is inheritered by two classes:
a. Success - data class, accepts object T in the constructor
b. Error - data class, accepts object R in the constructor
I need to create a function, which returns Result object. The function has to be created in a way:
- that the result of this function can be assigned to the variables of the following types:
Result<Number, String>
Result<Any, String>
- that the result of this function can NOT be assigned to the variables of the following types:
Result<Int, CharSequence>
Result<Int, Any>
That is class Result must be covariant on T parameter and invariant on R parameter.
You can use the declaration-site variance provided by Kotlin in the declaration of your Result class.
T-> By default T is invariantout T-> makes T covariantin T-> makes T contavariantExample:
A function can return Result as: