Search code examples
scalascala-option

How to flatten a Try[Option[T]]


I want to flatten a Try[Option[T]] into a Try[T]

Here is my code

def flattenTry[T](t: Try[Option[T]]) : Try[T] = {
  t match {
    case f : Failure[T] => f.asInstanceOf[Failure[T]]
    case Success(e) => 
      e match {
        case None => Failure[T](new Exception("Parsing error"))
        case Some(s) => Success(s)
      }
  }
}

Is there a better way ?


Solution

  • You could try something like this which is a little neater:

    val t = Try(Some(1))
    val tt = t.flatMap{
      case Some(i) => Success(i) 
      case None => Failure(new Exception("parsing error"))
    }
    

    More generically, this would be:

    def flattenTry[T](t: Try[Option[T]]) : Try[T] = {
      t.flatMap{
        case Some(s) => Success(s) 
        case None => Failure(new Exception("parsing error"))
      }    
    }
    

    The trick is to convert the Option into Try for using flatmap.