【问题标题】:Scala: Chain multiple functions with Try[T] as the return typeScala:使用 Try[T] 作为返回类型链接多个函数
【发布时间】:2021-06-19 04:50:44
【问题描述】:

我是 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()
}

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

【问题讨论】:

  • 这只是基本的flatMap 链接,任何关于 Scala 的基本教程都应该涵盖这一点。在深入尝试编写代码之前,最好先了解一下语言、stdlib 以及如何使用它。

标签: scala functional-programming try-catch


【解决方案1】:

简单而典型的for-comprehension就是这样:

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

你可以在互联网上找到很多关于这个主题的学习材料,但基本上这是flatMapmapwithFilterforeach 上的语法糖,适用于像你这样的案例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-06
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多