Scala“尝试”返回类型和异常处理
我是 scala 的新手,现在正在尝试完成练习。 我如何返回 无效
//Success: return the calculated price
//Failure: InvalidCartException
def calculateCartPrice(cart:Cart): Try[Price] = {
if(isCartValid(cart)) {
//Calculations happen here
return Try(Price(totalPrice));
}
}
def isCartValid(cart: Cart): Boolean = {
//THIS WORKS FINE
}
当功能返回类型为时,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的意思是“如何制作
尝试
包含异常” ,则使用fafer()
如下:然后,给定
尝试
您可以使用getorelse
获得成功的价值或抛出异常。If you mean "how to make the
Try
contain an exception", then use theFailure()
like below:Then, given a
Try
you can usegetOrElse
to get the value of success or throw the exception.尝试
将为您捕获异常,因此将可以将异常的代码放入其中。例如,如果您拥有的是
尝试
,并且想在拥有Fafer
的情况下抛出异常,则可以使用模式匹配来执行此操作:新手scala scala of scala 有很多有用的Scala的人(i在我学习时发现它非常宝贵。
Try
will catch the exception for you, so put the code that can throw the exception in there. For exampleIf what you have is a
Try
and you want to throw the exception when you have aFailure
, then you can use pattern matching to do that:The Neophyte's Guide to Scala has lots of useful information for people new to Scala (I found it invaluable when I was learning).