How can I (best) convert an Option into a Try?

myOption
  .toRight(new Exception("y"))
  .toTry

This code will return either a Success(x) if myOption is Some(x) or Failure(Exception("y")) if it is a None.


Short and simple

Try(option.get)

no need for fancy mapping. In case the option is empty you get an error like:

java.util.NoSuchElementException: None.get

If you start out with a Try from the get go with your for-comp then you can eliminate the match at the end. You can do this by forcing the Option to a Try via fold. Here's what that could look like:

def getValidBRefForReferencedA(aRef: ARef): Try[BRef] = {
  for {
    a <- get[A](aRef).fold[Try[A]](Failure[A](new OtherException("Invalid aRef supplied")))(Success(_))
    abRef = a.bRef
    _ <- validBRefs.find(_ == abRef).fold[Try[BRef]](Failure(new MismatchException("No B found matching A's B-ref")))(Success(_))
  } yield abRef
}

With this approach, you can get different exceptions for the two different checks. It's not perfect, but maybe it will work for you.


You can use an implicit conversion

  implicit class OptionOps[A](opt: Option[A]) {

    def toTry(msg: String): Try[A] = {
      opt
        .map(Success(_))
        .getOrElse(Failure(new NoSuchElementException(msg)))
    }
  }

Scala standard lib uses this type of approach. See http://docs.scala-lang.org/tutorials/FAQ/finding-implicits.html#companion-objects-of-a-type