我是 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 ,但本质上这是对 flatMap
、map
、withFilter
和foreach
适用于像您这样的情况。
关于Scala:以 Try[T] 作为返回类型链接多个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66747811/