2014-05-22 69 views
2

我在Scala有一个Seq [T],并且想要对每个元素做些什么。在成功的情况下,我希望将结果交给Seq创建并理解,但我不想在异常情况下产生任何结果。斯卡拉在成功的情况下产出,但不在例外情况下

我想是这样的:

val destinations = for(path <- files) { 
    try { 
    yield tryReadDestinations(path) 
    } catch { 
    case _ => log.error("Error happened :(") 
    } 
} 

但当然

这样的代码不能编译。我怎样才能实现这样的事情?

UPDATE:

我设法让这样的事情:

files 
    .map(a => tryExtractDestinationsFromAttachment(a)) 
    .filter { 
    case Success(d) => true 
    case Failure(_) => false 
    } 
    .map(t => t.get) 
    .flatten 

tryExtractDestinationsFromAttachment返回Try[String]

,但我相信这是可能使它simplier /更具可读性?

+0

你期望什么结果?如果成功搜集结果并在任何时候出现失败,其原因是什么? (全部或全部)? – maasg

回答

4

你可以包装每一个Try阅读和做一些事情,如:

files 
    .map(f => Try(tryReadDestinations(f))) 
    .map(t => t.recoverWith { case ex => log.error(ex); t }) 
    .flatMap(_.toOption) 
+0

我不想忽略错误,因为我需要记录它们。 – amorfis

+0

你可以''flatMap'将'Seq'设置为'Either',其中'left'结果是抛出异常,'right'结果是正常值。 –

+0

引入一个视图或一个迭代器是有意义的,这样集合就不会遍历三次。 –

0

这是你在找什么?

import scala.util.{Try, Success, Failure} 

def extractDestinationsFromAttachment(path: Path): Seq[Destination] = ??? 

val destinations = files flatMap { path => 
    Try(extractDestinationsFromAttachment(path)) match { 
    case Success(dests) => dests 
    case Failure(exception) => { log(exception); Nil } 
    } 
} 

所有extractDestinationsFromAttachment所要做的就是抛出一个错误消息的异常,如果它失败了,或者目的地的Seq如果成功。