如何(最好)将方法调用返回的选项转换为Try(优先级,尽管Either或scalaz \/甚至验证可能没问题),包括在适当的情况下指定Failure值?
例如,我有以下代码,感觉很笨,但至少做(大部分)工作:
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 { …Run Code Online (Sandbox Code Playgroud)