Hi, I'm playing a bit with the computation blocks; I'm trying to understand what is the best way to compose blocks for nested monads. As an example:
Copy code
val str1 = "hello".toOption().right()
val str2 = "world".toOption().right()
val output: Either<Any, Option<String>> = either {
option {
val value1 = str1.bind().bind()
val value2 = str2.bind().bind()
value1 + value2
}
}
I'm wondering if there is any "generic" way compose in order to obtain (for this example) an
eitherOption { }
block where I can call
.bind()
just one time. I know that Option and Either nested like this are not so useful, this is just for having a simple example 😃
s
simon.vergauwen
11/15/2021, 9:05 PM
With Multiple Receivers we can just do the following:
Copy code
context(EitherEffect<E>, OptionEffect)
suspend fun <E, A> Either<E, Option<A>.bind(): A = bind().bind()
simon.vergauwen
11/15/2021, 9:07 PM
Performance wise there is no penalty since it just uses
inline fold
underneath the hood
simon.vergauwen
11/15/2021, 9:08 PM
It’s currently not possible to defined that in Kotlin, unless you do some manual wiring
simon.vergauwen
11/15/2021, 9:09 PM
The only way to do this currently is to define:
Copy code
interface EitherOptionEffect : EitherEffect<E> OptionEffect {
suspend fun <E, A> Either<E, Option<A>.bind(): A
}
Which you can make concrete by doing something likee