Hi, I was looking at the `Either` source code and ...
# arrow
n
Hi, I was looking at the
Either
source code and out of curiosity I was wondering why functions like
map
,
fold
,
tap
... are member functions while
flatMap
,
getOrElse
and some other are extension functions.
s
flatMap
is an extension because of how generics work in Kotlin, so you can have a different error type after
flatMap
... or maybe ti was variance related.... I don't remember exactly
r
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:
Copy code
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:
Copy code
1.right() // inferred to Either<Nothing, Int>
would not unify properly with other expressions that would yield
Either<String, Nothing>
as compatible sub types.
n
Thanks for sharing the information 👍 👏