Pattern match on value of Either inside a for comprehension?

前端 未结 4 1800
無奈伤痛
無奈伤痛 2021-01-18 04:58

I have a for comprehension like this:

for {
      (value1: String, value2: String, value3: String) <- getConfigs(args)
      // more stuff using those val         


        
4条回答
  •  隐瞒了意图╮
    2021-01-18 05:41

    I guess you want your loop to run only if the value is a Right. If it is a Left, it should not run. This can be achieved really easy:

    for {
      (value1, value2, value3) <- getConfigs(args).right.toOption
      // more stuff using those values
    }
    

    Sidenote: I don't know whats your exact use case, but scala.util.Try is better suited for cases where you either have a result or a failure (an exception).
    Just write Try { /*some code that may throw an exception*/ } and you'll either have Success(/*the result*/) or a Failure(/*the caught exception*/).
    If your getConfigs method returns a Try instead of Either, then your above could would work without any changes.

提交回复
热议问题