How can I (best) convert an Option returned by a method call into a Try (by preference, although an Either or a scalaz \/
or even a Validation might be OK) including specifying a Failure value if appropriate?
For example, I have the following code, which feels kludgy, but does at least do (most of) the job:
import scala.util._
case class ARef(value: String)
case class BRef(value: String)
case class A(ref: ARef, bRef: BRef)
class MismatchException(msg: String) extends RuntimeException(msg)
trait MyTry {
// Given:
val validBRefs: List[BRef]
// Want to go from an Option[A] (obtained, eg., via a function call passing a provided ARef)
// to a Try[BRef], where the b-ref needs to be checked against the above list of BRefs or fail:
def getValidBRefForReferencedA(aRef: ARef): Try[BRef] = {
val abRef = for {
a <- get[A](aRef) // Some function that returns an Option[A]
abRef = a.bRef
_ <- validBRefs.find(_ == abRef)
} yield (abRef)
abRef match {
case Some(bRef) => Success(bRef)
case None => Failure(new MismatchException("No B found matching A's B-ref"))
}
}
}
It feels like there should be a way for the final match to be morphed into a map or flatMap or similar construct and incorporated into the preceeding for comprehension.
Also, I would prefer to be able to specify a different failure message if the call to return an Option[A] from the ARef failed (returned None) compared to the BRef check failing (I only care about knowing one reason for the failure, so a scalaz Validation doesn't feel like the ideal fit).
Is this a suitable place to use a monad transformer? If so, does scalaz provide a suitable one, or can someone give an example of what it would look like?
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.