Scala:以 Try[T] 作为返回类型链接多个函数

标签 scala functional-programming try-catch

我是 Scala 函数式编程的新手,正在开发一个模块,其中每个运算符(类实例/对象)都链接在一起。这些运算符只有一个函数,并且返回 Try[T]。我正在寻找一种更易读的方式将它们链接在一起。

trait Mapper {
    def map(in: T): Try[T]
}

trait Reducer {
    def reduce(in: T): Try[T]
}

trait Grouper {
    def group(in: T, batchSize: int): Try[T]
}

可以说我已经为这些特征创建了实现。现在在我的主要功能中,我可以做类似的事情

object MyApp extends App {
    val mapper: Mapper = ...
    val reducer: Reducer = ...
    val grouper: Grouper = ...  

    def run(): Try[Unit] = {
        val inp: T = ...
        mapper.map(inp) match {
            case Success(x) => reducer.reduce(x) match {
                case Success(y) => grouper.group(x) match {
                    case Success(z) => ..// some other function call
                    case Failure(e) => throw e
                }
                case Failure(e) => throw e
                }
           case Failure(e) => throw e
        }
    }

   run()
}

有没有办法,我可以避免所有这些成功、失败模式匹配,并以更好的方式做到这一点?

最佳答案

简单且典型的for-compressive是这样的:

def run(): Try[Unit] = {
    val inp: T = ...
    for {
     mapResult <- mapper.map(inp)
     reduceresult <- reducer.reduce(mapResult)
     groupResult <- grouper.group(x)
    } yield ()
}

你可以在互联网上找到很多关于这个主题的学习 Material ,但本质上这是对 flatMapmapwithFilterforeach 适用于像您这样的情况。

关于Scala:以 Try[T] 作为返回类型链接多个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66747811/

相关文章:

scala - 任何支持 SBT 的 IDE?

java - 函数和谓词参数不明确?

java - 在 try block 完成后延迟 Finally block

C++ : how to return the value from an out of bounds array with exception handling?

r - 我如何在R中打印实际的错误消息

scala - 如何使用 Scala Actors 的同步发送来摆脱向下转换?

scala - future [A] 与 future [Throwable\/A]

scala - 使用 scala Type 设置类型参数(通过 TypeTag?)

functional-programming - 在 OCaml 中实现快速排序 : don't understand what's going wrong?

validation - 带TextFormField的onLeave-Flutter/Dart