If I have the following methods return types:
Future[Option[User]]
Either[Throwable, String]
Option[Int]
There is no way I can have these in for comprehensions because the types don't line up correct? But types it is meant that the containers are all different i.e. Future, Either and an Option.
So do perform a for-comprehension we have to lift some or all of these types into a common type then?
If someone can detail the thought process that would be really helpful.
CodePudding user response:
There is no way I can have these in for comprehensions because the types don't line up correct?
Yes.
So do perform a for-comprehension we have to lift some or all of these types into a common type then?
Exactly.
If someone can detail the thought process that would be really helpful.
Usually, you find a type that is the most powerful one and convert everything into that type. In your case that would be Future
Something like this:
for {
userOpt <- futureUser
str <- Future.fromTry(eitherString.toTry)
i <- Future.fromTry(iOpt.toRight(left = someEx).toTry)
}
Although, depending on the particular logic you have you may avoid that and just lif everything inside a single map on the first Future
Or, sometimes a transformer may also be useful.
As always, it depends on the exact use case.
