简体   繁体   中英

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. 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. Try does have handy getOrElse and toOption methods which could help us convert cases of Failure to None .

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

For map if you wish to throw out the failures, you can do something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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