Kristian Nedrevold
09/13/2022, 6:40 PMfun foo(): Either<Err, Ok>
val res = foo().map { bar(it) }.mapLeft { return it }
and foo() is Err?Kristian Nedrevold
09/13/2022, 6:47 PMval res = bar(foo().getOrHandle { return it })
Does what I want here I think?qohatpp
09/13/2022, 7:44 PMval res = foo().map { bar(it) }.mapLeft { return it }
1. if foo() is Right bar(it) is going to be executed and you will have a Right(bar(Ok)) as result, which is an Either<Err, Whatever Your bar(Ok) type is>
2. if foo() is Left then your mapLeft is gonna be executed giving a Left(Err) as result.
In your example seems like mapLeft is not longer necessary because you are returning it , so you actually are not mapping the left value.
Regarding to val res = bar(foo().getOrHandle { return it }) , At first glance seems like It's not the same thing.Lukasz Kalnik
09/14/2022, 5:52 AMreturn within a lambda.Lukasz Kalnik
09/14/2022, 5:53 AMmapLeft ( it ) or getOrHandle ( it )Lukasz Kalnik
09/14/2022, 5:57 AMmapLeft ( it ) and getOrHandle ( it ) both are no-ops (they don't change the incoming data)Lukasz Kalnik
09/14/2022, 5:59 AMmapLeft() returns the result of the lambda wrapped in a Left and getOrHandle() returns the result of a lambda unwrapped (as in "get what's inside the Either or handle the left result")Lukasz Kalnik
09/14/2022, 6:00 AMLeft("hello").mapLeft { it.length ) // Left(5)
Left("hello").getOrHandle { it.length) // 5Lukasz Kalnik
09/14/2022, 6:02 AMgetOrElse when you just want to provide a default value and don't need to access the contents of the original `Left`:
Left("hello").getOrElse { "default text" ) // "default text"Lukasz Kalnik
09/14/2022, 6:13 AMRight or provide some default value if it's a Left, and then use it inside the bar(), getOrElse() is the way to go.Olaf Gottschalk
09/14/2022, 9:15 PM