在Scala中将列表[Try [A]]转换为列表[A]
问题描述:
我想从输入数据中过滤掉错误的输入.我目前正在使用 scala.util.Try
来包装所有异常.以下是一个简单的示例,其中3I抛出 NumberFormatException
.我想知道在Scala中是否有更好的方法?
I want to filter out bad input from input data. I'm currently using scala.util.Try
to wrap any exceptions. Following is a simple example where 3I throws a NumberFormatException
. I was wondering if there is a better way of doing this in Scala ?
val data = List ( ("Joe", "20"), ("James", "30"), ("Pete", "3I") )
scala> val parsedData = data.map{ d => Try{Person( d._1, d._2.toInt ) }}
parsedData: List[scala.util.Try[Person]] = List(Success(Person(Joe,20)), Success(Person(James,30)), Failure(java.lang.NumberFormatException: For input string: "3I"))
scala> val validdata = parsedData.map{ x => x match {
| case Success(s) => Some(s)
| case Failure(f) => None }
| }
validdata: List[Option[Person]] = List(Some(Person(Joe,20)), Some(Person(James,30)), None)
scala> validdata.flatten
res13: List[Person] = List(Person(Joe,20), Person(James,30))
答
使用 collect
仅保留与所需模式匹配的值:
Use collect
to keep only the values that match the pattern you desire:
parsedData collect { case Success(x) => x }
这也可以工作,尽管我认为还不是很清楚:
This will also work, though I don't think it's quite as clear:
parsedData.flatMap(_.toOption)