문제

I just start to be used to deal with monadic operations. For the Option type, this Cheat Sheet of Tony Morris helped: http://blog.tmorris.net/posts/scalaoption-cheat-sheet/

So in the end it seems easy to understand that:

  • map transforms the value of inside an option
  • flatten permits to transform Option[Option[X]] in Option[X]
  • flatMap is somehow a map operation producing an Option[Option[X]] and then flattened to Option[X]

At least it is what I understand until now.


For Either, it seems a bit more difficult to understand since Either itself is not right biaised, does not have map / flatMap operations... and we use projection.

I can read the Scaladoc but it is not as clear as the Cheat Sheet on Options. Can someone provide an Either Sheet Cheat to describe the basic monadic operations?

It seems to me that Either.joinRight is a bit like RightProjection.flatMap and seems to be the equivalent of Option.flatten for Either.

It seems to me that if Either was Right biaised, then Either.flatten would be Either.joinRight no?

In this question: Either, Options and for comprehensions I ask about for comprehension with Eiher, and one of the answers says that we can't mix monads because of the way it is desugared into map/flatMap/filter.

When using this kind of code:

def updateUserStats(user: User): Either[Error,User] = for {
  stampleCount <- stampleRepository.getStampleCount(user).right
  userUpdated <- Right(copyUserWithStats(user,stampleCount)).right
  userSaved <- userService.update(userUpdated).right
} yield userSaved

Does this mean that all my 3 method calls must always return Either[Error,Something]? I mean if I have a method call Either[Throwable,Something] it won't work right?


Edit: Is Try[Something] exactly the same as a right-biaised Either[Throwable,Something]?

도움이 되었습니까?

해결책

Either was never really meant to be an exception handling based structure. It was meant to represent a situation where a function really could possible return one of two distinct types, but people started the convention where the left type is a supposed to be a failed case and the right is success. If you want to return a biased type for some pass/fail type business checks logic, then Validation from scalaz works well. If you have a function that could return a value or a Throwable, then Try would be a good choice. Either should be used for situations where you really might get one of two possible types, and now that I am using Try and Validation (each for different types of situations), I never use Either any more.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top