One possible way is to use Try(o.get) to convert o: Option to o: Try .
This is very eloquent, but it throws and throws an exception when handling None , which can sometimes be a performance issue (or sometimes it concerns ideological / code rules). However, the code is so concise and well readable, I think it's worth mentioning:
def flattenTry[T](t: Try[Option[T]]) : Try[T] = { t.flatMap(o => Try(o.get)) }
Note. It is not recommended to use it, but for completeness: an even shorter version is possible that throws / catches even if Try is a failure:
def flattenTry[T](t: Try[Option[T]]) : Try[T] = { Try(t.get.get) }
source share