Hey, what happens when you have code like ```fun f...
# arrow
k
Hey, what happens when you have code like
Copy code
fun foo(): Either<Err, Ok>
val res = foo().map { bar(it) }.mapLeft { return it }
and foo() is Err?
Copy code
val res = bar(foo().getOrHandle { return it })
Does what I want here I think?
q
Copy code
val 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.
l
Just a hint, you cannot have
return
within a lambda.
It should be
mapLeft ( it )
or
getOrHandle ( it )
mapLeft ( it )
and
getOrHandle ( it )
both are no-ops (they don't change the incoming data)
The difference between them is that
mapLeft()
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")
Copy code
Left("hello").mapLeft { it.length ) // Left(5)
Left("hello").getOrHandle { it.length) // 5
There is also
getOrElse
when you just want to provide a default value and don't need to access the contents of the original `Left`:
Copy code
Left("hello").getOrElse { "default text" ) // "default text"
So I guess if your use case is to "unwrap" the value if it's a
Right
or provide some default value if it's a
Left
, and then use it inside the
bar()
,
getOrElse()
is the way to go.
o
The "return it" inside the mapLeft makes the function which contains the instruction return it, the Err. Nothing gets put into res at all. So the type of res will be Either<Nothing, type of bar>