niltsiar
11/11/2021, 8:19 AMEither
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.stojan
11/11/2021, 8:48 AMflatMap
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 exactlyraulraja
11/11/2021, 12:58 PMout
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.niltsiar
11/11/2021, 1:26 PM