Hi
@niltsiar, to expand on
@stojan point:
Either is defined as covariant
out
in both its type arguments but if we were to define flatMap inside Either:
public inline fun <B, C> flatMap(f: (B) -> Either<A, C>): Either<A, C>
in the lambda
f
A
appears in contravariant
in
position over the lambda return type. If we move it to an extension then
A
is no longer coming from the instance but from the environment in invariant position which is acceptable. We could have included flatMap inside the Either data type if we had changed Either’s type arguments to be invariant but this would cascade poorly for inference. for example:
1.right() // inferred to Either<Nothing, Int>
would not unify properly with other expressions that would yield
Either<String, Nothing>
as compatible sub types.