cov*_*efe 7 scala pattern-matching either for-comprehension
我有这样的理解:
for {
(value1: String, value2: String, value3: String) <- getConfigs(args)
// more stuff using those values
}
Run Code Online (Sandbox Code Playgroud)
getConfigs返回一个Either[Throwable, (Seq[String], String, String)],当我尝试编译时,我收到此错误:
value withFilter is not a member of Either[Throwable,(Seq[String], String, String)]
Run Code Online (Sandbox Code Playgroud)
如何Either在for comprehension中使用此方法(返回一个)?
我猜你希望循环仅在值为 Right 时运行。如果是左派,就不应该竞选。这可以很容易实现:
for {
(value1, value2, value3) <- getConfigs(args).right.toOption
// more stuff using those values
}
Run Code Online (Sandbox Code Playgroud)
旁注:我不知道您的确切用例是什么,但scala.util.Try更适合您有结果或失败(例外)的情况。
只要写下Try { /*some code that may throw an exception*/ },您就会拥有Success(/*the result*/)或Failure(/*the caught exception*/).
如果您的getConfigs方法返回 aTry而不是Either,那么您的上述内容无需任何更改即可工作。
| 归档时间: |
|
| 查看次数: |
486 次 |
| 最近记录: |