tim
06/03/2020, 5:37 PMval 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:
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?aballano
06/03/2020, 9:37 PMval 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 💪aballano
06/03/2020, 9:38 PMtim
06/04/2020, 7:48 AMaballano
06/04/2020, 8:21 AMtim
06/04/2020, 8:21 AMaballano
06/04/2020, 8:21 AMaballano
06/04/2020, 8:23 AMtim
06/04/2020, 8:26 AMval 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)
}
}
tim
06/04/2020, 8:28 AMaballano
06/04/2020, 9:22 AM