Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a List[Try[A]] to List[A] in 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))
like image 261
Soumya Simanta Avatar asked Jan 15 '15 01:01

Soumya Simanta


1 Answers

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)
like image 79
Michael Zajac Avatar answered Nov 06 '22 10:11

Michael Zajac