I have been reviewing Scala knowledge and have been going circles about the variance/lower bound.
In the 'functional programming in scala' book, the Either type, it has below signature/exercise (Implement versions of flatMap, orElse on Either that operate on the Right value).
sealed trait Either[+E,+A] {
def flatMap[EE >: E, B](f: A => Either[EE, B]): Either[EE, B] = ???
def orElse[EE >: E, B >: A](b: => Either[EE, B]): Either[EE, B] = ???
}
and the note of the book says
when mapping over the right side, we must promote the left type parameter to some supertype, to satisfy the +E variance annotation. similarly for 'orElse'
My question are:
- why do not we have to say
B >: Ain theflatMapfunction? we do not need to satisfy+A? - why does
orElsesignature requiresB >: A?
I understand method parameters count as contravariant positions, so we could not possibly have A or E in the method's parameter. i.e. the 'return type' of the f or b could not have E or A in it.
Maybe I am missing something, in relation to the fundamental knowledge of subtyping/lower bound/function as parameter.
Please help me to understand it with maybe some concrete examples.
p.s. Most articles, about variance or upper/lower bound, I found have only 1 type parameter in the class/trait.