Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 877
Yann Moisan Avatar asked Nov 26 '13 13:11

Yann Moisan


Video Answer


1 Answers

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.

like image 186
cmbaxter Avatar answered Sep 22 '22 02:09

cmbaxter