Scala处理缺少嵌套的Optionals

Ale*_*vic 3 scala

假设我有一个对象A,它可能有一个Option B,也可能引用另一个可选对象C(嵌套的选项)

我已经看到了几种访问方式C,比如for-comprehension,模式匹配或者flatMap看起来都很好看.但是,如果我必须返回某种错误消息或抛出异常,如果B或者C丢失或者提供类似cannot execute because B is missing或的消息C not set怎么办?我只能回归(嘲笑):

if(a.b.isDefined)
{
   if(a.b.c.isDefined)
   {
           //do work
   }
   else throw new Exception1 //or call something other
}
else throw new OtherException //or do something other
Run Code Online (Sandbox Code Playgroud)

我怎么能以功能或更流畅的方式处理?

Lee*_*Lee 6

如果值为none,您可以添加一个方法来转换Option为a Try和fail

implicit class OptionWrapper[T](val o: Option[T]) extends AnyVal {
    def tryGet(e: => Throwable): Try[T] = o match {
        case Some(x) => Success(x)
        case None => Failure(e)
    }   
}
Run Code Online (Sandbox Code Playgroud)

那么你可以做到

a.b.tryGet(new OtherException).flatMap(_.tryGet(new Exception1))
Run Code Online (Sandbox Code Playgroud)