对于comprensions和排队解释的类型
For comprensions and the types lining up explanation
如果我有以下方法return类型:
Future[Option[User]]
Either[Throwable, String]
Option[Int]
我无法理解这些内容,因为类型排列不正确?但是类型意味着容器都是不同的,即 Future、Either 和 Option。
那么执行 for-comprehension 我们必须将这些类型中的一些或所有提升为通用类型吗?
如果有人能详细说明思考过程,那将非常有帮助。
There is no way I can have these in for comprehensions because the types don't line up correct?
是的。
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.
通常,您会找到一种最强大的类型,然后将所有内容都转换为该类型。在你的情况下是 Future
像这样:
for {
userOpt <- futureUser
str <- Future.fromTry(eitherString.toTry)
i <- Future.fromTry(iOpt.toRight(left = someEx).toTry)
}
不过,根据您的特定逻辑,您可以避免这种情况,只需在第一个 Future
中将所有内容提升到单个 map
中
或者,有时变压器也可能有用。
一如既往,这取决于具体的用例。
如果我有以下方法return类型:
Future[Option[User]]
Either[Throwable, String]
Option[Int]
我无法理解这些内容,因为类型排列不正确?但是类型意味着容器都是不同的,即 Future、Either 和 Option。
那么执行 for-comprehension 我们必须将这些类型中的一些或所有提升为通用类型吗?
如果有人能详细说明思考过程,那将非常有帮助。
There is no way I can have these in for comprehensions because the types don't line up correct?
是的。
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.
通常,您会找到一种最强大的类型,然后将所有内容都转换为该类型。在你的情况下是 Future
像这样:
for {
userOpt <- futureUser
str <- Future.fromTry(eitherString.toTry)
i <- Future.fromTry(iOpt.toRight(left = someEx).toTry)
}
不过,根据您的特定逻辑,您可以避免这种情况,只需在第一个 Future
中将所有内容提升到单个 map
中
或者,有时变压器也可能有用。
一如既往,这取决于具体的用例。