I want to filter out bad input from input. I am currently using scala.util.Try to wrap any exceptions. The following is a simple example where 3I throws a NumberFormatException . I was wondering if there is a better way to do 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))
source share