scala - 在 flatMap 中使用 Try

标签 scala

我正在编写我自己的类 Success 或 Error。我想创建一种从 Try 构建 SuccessOrError 的方法,然后使用 Try 而不是丑陋的 try-catch平面 map 。但我被困在这一点上。我应该如何最好地编写一个函数 fromTry 以便能够像这样编写?
案例 SuccessOrError.Success(v) ⇒ SuccessOrError.fromTry(Try(f(v)))

  enum SuccessOrError[+V]:

    case Success(x: V) extends SuccessOrError[V]

    case Error(e : Throwable) extends SuccessOrError[V]

    def flatMap[Q](f: V ⇒ SuccessOrError[Q]): SuccessOrError[Q] =
      this match
        case SuccessOrError.Success(v)   ⇒ try f(v) catch case NonFatal(e) => SuccessOrError.Error(e) 
        case SuccessOrError.Error(e)  ⇒ SuccessOrError.Error(e)


object SuccessOrError:
   def fromTry[Q](f: Try[Q]): SuccessOrError[Q] = ???

最佳答案

Try 转换为另一个错误模型是很常见的做法。也许考虑一下他们如何在 scala-cats 库中处理它作为灵感

Validated

  /**
   * Converts a `Try[A]` to a `Validated[Throwable, A]`.
   */
  def fromTry[A](t: Try[A]): Validated[Throwable, A] =
    t match {
      case Failure(e) => invalid(e)
      case Success(v) => valid(v)
    }

Either

  /**
   * Converts a `Try[A]` to a `Either[Throwable, A]`.
   */
  def fromTry[A](t: Try[A]): Either[Throwable, A] =
    t match {
      case Failure(e) => left(e)
      case Success(v) => right(v)
    }

ApplicativeError

  /**
   * If the error type is Throwable, we can convert from a scala.util.Try
   */
  def fromTry[A](t: Try[A])(implicit ev: Throwable <:< E): F[A] =
    t match {
      case Success(a) => pure(a)
      case Failure(e) => raiseError(e)
    }

注意在快乐和不快乐的情况下进行简单模式匹配的模式(不好的双关语,applogies),所以我们可以尝试模仿它

def fromTry[Q](f: Try[Q]): SuccessOrError[Q] = 
  f match {
    case scala.util.Failure(e) => SuccessOrError.Error(e)
    case scala.util.Success(v) => SuccessOrError.Success(v)
  }

关于scala - 在 flatMap 中使用 Try,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66985079/

相关文章:

scala - <not computed> 关于 Scala 中的集合输出

linux - 在 Scala 脚本中自行修改类路径?

java - 将 Java 和 Scala 集成到一个项目中

java - scala maven 插件没有将 scala 文件打包到 jar 中

scala - sbt 发布到 Maven 中心失败,没有公钥错误

java - 从 Spark 中的类别列表创建一个热编码 vector

java - 如何将参数传递给 Spark 中 mapPartitions 的用户定义函数?

scala - 如何将依赖项添加到 SBT 构建文件

scala - 在 Slick 中使用 DatabaseConfig 和 Database 有什么区别?

java - 当我运行 scala 应用程序时如何修复 "NoClassDefFoundError: midterm/Main"?