https://kotlinlang.org logo
#arrow
Title
# arrow
m

mat

12/08/2023, 11:23 PM
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

mitch

12/09/2023, 1:01 AM
@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

CLOVIS

12/09/2023, 10:57 AM
Copy code
val lefts = someList.filterIsInstance<Either.Left<A>>().map { it.value }

val rights = someList.filterIsInstance<Either.Right<B>>().map { it.value }
🙌 2
m

mat

12/10/2023, 9:18 PM
Ahh those two seem like usable options. Thanks
m

mat

12/12/2023, 4:57 PM
Wow, that is perfect. Is there some way to mark a thread as answered or done in Slack?
c

CLOVIS

12/12/2023, 4:57 PM
Not particularly. Some people use for that, but most people don't do anything 👍
1
4 Views