如何处理退货 [英] how do I process returned Either
本文介绍了如何处理退货的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果是scala函数,则
if a scala function is
def A(): Either[Exception, ArrayBuffer[Int]] = {
...
}
什么是处理返回结果的正确方法?
val a = A()
和?
what should be the right way to process the returned result?
val a = A()
and ?
推荐答案
我通常更喜欢使用fold
.您可以像地图一样使用它:
I generally prefer using fold
. You can use it like map:
scala> def a: Either[Exception,String] = Right("On")
a.fold(l => Left(l), r => Right(r.length))
res0: Product with Either[Exception,Int] = Right(2)
或者您可以像模式匹配一样使用它:
Or you can use it like a pattern match:
scala> a.fold( l => {
| println("This was bad")
| }, r => {
| println("Hurray! " + r)
| })
Hurray! On
或者您可以像Option
中的getOrElse
一样使用它:
Or you can use it like getOrElse
in Option
:
scala> a.fold( l => "Default" , r => r )
res2: String = On
这篇关于如何处理退货的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文