https://kotlinlang.org logo
Title
r

Rohde Fischer

07/31/2022, 1:59 PM
when working with an
Either
I sometimes run into having multiple results where I need the results for another call. There I'm usually end up in an ugly structure with nested `flatMap`s. E.g.:
val result1 = foo() // : Either<Error, Result1>
val result2 = foo() // : Either<Error, Result2>
val result3 = foo() // : Either<Error, Result3>

val transformed = result1.flatMap { res1 ->
    result2.flatMap { res2 ->
        result3.flatMap { res3 -> someCall(res1, res2, res3) }
    }
}
isn't there a nicer way to do this?
one shot (that I'm not satisfied with) is to use a
flatMap
curry structure:
Right(someCall)
    .flatMap { fn ->
        foo().map { res1 -> {res2: Result2, res3: Result3 -> fn(res1, res2, res3) } }
    }
    .flatMap { fn ->
        foo().map { res2 -> {res3: Result3 -> fn(res2, res3) } }
    }
    .flatMap { fn ->
        foo().map { fn(it) } }
    }
y

Youssef Shoaib [MOD]

07/31/2022, 9:18 PM
Use the
either
continuation block
either<Error> {
  someCall(result1.bind(), result2.bind(), result3.bind()
}
Or alternatively use
Either.zip
result1.zip(result2, result3, ::someCall)
r

Rohde Fischer

08/01/2022, 7:11 AM
thanks, I will look into that 🙂