简体   繁体   English

处理Scala集合中的异常

[英]Handling exceptions in Scala collections

You have a Scala collection (an iterator, in this case) that you wish to filter or map , where the function doing so can raise an exception. 您有一个Scala集合(在本例中是一个迭代器),您希望filtermap ,这样做的函数可以引发异常。 You don't want the entire resulting collection being thrown out - only that member. 您不希望抛出整个结果集合 - 只有该成员。 How do you do that? 你是怎样做的?

I tried doing something like: 我尝试过这样的事情:

 collection.filter(Try(_.predicate))

but wasn't able to get that to work (and am not sure that that's the proper idiom in the first place!) 但是无法让它发挥作用(并且我不确定这首先是正确的成语!)

You're very close. 你很近。 Try something like: 尝试类似的东西:

collection.filter(x => Try(x.predicate).getOrElse(false))

Depends on which you want to do. 取决于你想做什么。 In the case of filter , the predicate still needs to be boolean, and Try[T] is most certainly not. filter的情况下,谓词仍然需要是布尔值,而Try[T]肯定不是。 Try does have handy getOrElse and toOption methods which could help us convert cases of Failure to None . Try有方便的getOrElsetoOption方法,可以帮助我们将Failure案例转换为None

collection.filter(x => Try(predicate).getOrElse(false))

For map if you wish to throw out the failures, you can do something like this: 对于map如果你想抛弃失败,你可以这样做:

collection.flatMap(x => Try(...).toOption)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM