我如何(最好)将选项转换为尝试? [英] How can I (best) convert an Option into a Try?

查看:40
本文介绍了我如何(最好)将选项转换为尝试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何(最好)将方法调用返回的 Option 转换为 Try(根据偏好,尽管可以使用任何或 scalaz \/ 甚至验证),包括指定一个如果合适,故障值?

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.

此外,与 BRef 检查失败相比,如果从 ARef 返回 Option[A] 的调用失败(返回 None),我希望能够指定不同的失败消息(我只关心知道一个原因)失败,所以 scalaz 验证并不适合).

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).

这是一个适合使用 monad 转换器的地方吗?如果是这样,scalaz 是否提供了合适的一个,或者有人可以举一个例子来说明它会是什么样子?

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?

推荐答案

如果您从一开始就使用 Try 开始使用 for-comp,那么您可以在最后消除匹配.您可以通过 foldOption 强制为 Try 来实现.这可能是这样的:

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.

这篇关于我如何(最好)将选项转换为尝试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆