Hi all, another newb question ​sor​ry​ :slightly_s...
# arrow
t
Hi all, another newb question ​sor​ry​ 🙂 I'm trying to figure out how to combine multiple Eithers into one Either where their Rs form a list... Something like this:
Copy code
val a = Either.right(1) // or left
val b = Either.right(2) // or left
val c = Either.right(3) // or left

val d = // magic

d // Either<Nothing, List<Int>>
I've tried playing with flatMap, but i end up with flatMaps inside flapMaps ... which isn't very nice:
Copy code
val d = a.flatMap { a ->
 b.flatMap {
   Either.right(listOf(a, it))
 }
}
...
I think I'm just missing something basic here as I cant imagine my use case here is unique?
a
just a side comment here just in case: chaining flatMaps is not something bad per-se, obviously if you have many you might want to clean it up a bit and mapN is the perfect solution for that 👌 Alternatively if you don’t have many eithers and you like the syntax, you can try an fx block over Either in this case, although it’s a bit more manual:
Copy code
val d = Either.fx {
  val aa = a.bind()
  val bb = b.bind()
  val cc = c.bind()
  listOf(aa, bb, cc)
}
I personally prefer the mapN in this case, but the fx block has it’s places as well. Although is not something very FP related, but more of a way of writing functional code in an imperative way with the same benefits 💪
👍 1
🙏 1
ah, and don’t need to be sorry for asking questions, we’re happy to help 😉 as you can see by the amount of answers you got as well 😂
🙏 1
👍 1
t
What does bind do when called on an Either? I assume a/b/c are eithers and so it pulls out R? The syntax is a bit more concise here so might give this a try actually. Plus the fx block makes it clear that I'm interacting with a boundary which is exactly what I'm doing in my actually use case. Is this syntax much different than Either.catch? I guess Either.fx is using suspend/coroutines under hood ... so could it be overkill in my use case because its introducing coroutines unnecessarily?
a
bind effectively pulls out the value, it’s like a flatmap
t
and if its a Left?
a
then it stops the processing at that point and returns, like a flatmap that won’t continue
regarding being overkill, I don’t think so, coroutines are lightweight and could actually help you to do processing in a different thread actually
👍 1
t
Ahh okay so just tried this out wrt there being a left value inside the Either.fx:
Copy code
val a = getEither(1)
val b = getEither(2)

val d = Either.fx<String, List<Int>> {
    val aa = a.bind()
    val bb = b.bind()
    listOf(aa, bb)
}

println(d) -> // Sometimes I get Left(!!) and sometimes I get Right(1, 2)

fun getEither(value: Int) : Either<String, Int> {
    return if (Random.nextBoolean()) {
        Either.left("ouch!")
    } else {
        Either.right(value)
    }
}
Wrt Ether.catch vs Either.fx ... it appears that bind() is only available inside the .fx block ... so for different use cases
a
indeed 👌