在非功能性语言中,我可能会执行以下操作:
try {
// some stuff
} catch Exception ex {
return false;
}
// Do more stuff
return true;
但是,在Scala中,这种模式显然是不正确的。如果我的scala代码如下所示:
try {
// do some stuff
}
catch {
case e: Exception => // I want to get out of here and return false
)
}
// do more stuff
true
我该怎么做呢?我当然不想使用“ return”语句,但是我也不想删除并“做更多的事情”并最终返回true。
您想要表示一个可以成功执行或表示已发生错误的计算。那是Try
monad的完美用例。
import scala.util.{ Try, Success, Failure }
def myMethod: Try[Something] = Try {
// do stuff
// do more stuff
// if any exception occurs here, it gets wrapped into a Failure(e)
}
因此,您将返回aTry
而不是a Bool
,这将更加清晰明了。
用法示例:
myMethod match {
case Success(x) => println(s"computation succeded with result $x")
case Failure(e) => println(s"computation failed with exception $e.getMessage")
}
如果您甚至不关心异常,但只想在成功的情况下返回值,则可以将转换Try
为Option
。
def myMethod: Option[Something] = Try {
// do stuff
// do more stuff
// return something
// if any exception occurs here, it gets wrapped into a Failure(e)
}.toOption
myMethod match {
case Some(x) => println(s"computation succeded with result $x")
case None => println("computation failed")
}
要回答评论中的问题,您可以
Try {
// do stuff
} match {
case Failure(_) => false
case Success(_) =>
// do more stuff
// true
}
尽管我建议在有意义的Boolean
时候返回比a更有意义的东西。
当然可以嵌套
Try {
// do stuff
} match {
case Failure(_) => false
case Success(_) =>
// do more stuff
Try {
// something that can throw
} match {
case Failure(_) => false
case Success(_) =>
// do more stuff
true
}
}
但是您应该考虑将这些Try
块放入单独的函数中(返回Try
)。
最终,我们可以利用Try
单子这一事实,并执行类似的操作
Try { /* java code */ }.flatMap { _ =>
// do more stuff
Try { /* java code */ }.flatMap { _ =>
// do more stuff
Try { /* java code */ }
}
} match {
case Failure(_) => false // in case any of the Try blocks has thrown an Exception
case Success(_) => true // everything went smooth
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句