Hey fellas, I'm somewhat confused about the behavi...
# arrow
m
Hey fellas, I'm somewhat confused about the behaviour of Either. How do I retrieve the value out of a Left? Basically, my code is this:
Copy code
val results = someList.map(this::createsEitherResultOrErrorDescription)
if (results.any {it.isRight() }) return Right() // GET ALL RIGHTS HERE

return Left(consumesListOfResults(results.map {}) // GET ALL LEFTS HERE
I have found this super ugly hack here for retrieving the lefts:
Copy code
val results = results.map { it.merge() as MyResult }
But it's not very nice. For the Right case there is Either.getOrNull(), but I don't see a value for LEfts anywhere. In the ideal case there would be these two extension functions:
Copy code
List<Either<A,B>>.getAllLefts(): List<A>
List<Either<A,B>>.getAllRights(): List<B>
1
m
@mat you can leverage typesafe builders e.g
Copy code
fun List<Either<L, R>>.getLefts() = 
  buildList {
    this@getLefts.forEach { either ->
      either.onLeft { add(it) }
    }
  }
c
Copy code
val lefts = someList.filterIsInstance<Either.Left<A>>().map { it.value }

val rights = someList.filterIsInstance<Either.Right<B>>().map { it.value }
🙌 2
m
Ahh those two seem like usable options. Thanks
m
Wow, that is perfect. Is there some way to mark a thread as answered or done in Slack?
c
Not particularly. Some people use for that, but most people don't do anything 👍
1