本文介绍了scala 中的链接函数调用(或等效于 Ruby 的 yield_self)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是链接函数调用的惯用方式,在每个函数调用之间传递结果,并在 Scala 中提供参数?

What is an idiomatic way of chaining function calls, passing results between each with parameters supplied on the way in Scala?

这是一个例子:

def a(x : A, param : String) : A = x
def b(x : A, param : String) : A = x
def c(x : A, param : String) : A = x
def d(x : A, param : String, anotherParam : String) : A = x

val start = A()

d(c(b(a(start, "par1"), "par2"), "par3"), "par4", "anotherPar")

我想到的一种方法是 Ruby 的 Kernel#yield_self,它允许执行以下操作:

One approach that comes to my mind is Ruby's Kernel#yield_self which allows to do the following:

start
  .yield_self {|x| a(x, "par1") }
  .yield_self {|x| b(x, "par2") } 
  .yield_self {|x| c(x, "par3") } 
  .yield_self {|x| d(x, "par4", "anotherPar) } 

推荐答案

您可以将一系列功能组合成一个功能:

You may combine chain of functions into one function:

val start = new A()

val func: (A => A) =
  ((x: A) => a(x, "par1"))
    .andThen(b(_, "par2"))
    .andThen(c(_, "par3"))
    .andThen(d(_, "par4", "anotherPar"))

func(start)

但我不确定这是否是您的目标.

But I'm not sure if it's a your goal.

这篇关于scala 中的链接函数调用(或等效于 Ruby 的 yield_self)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 07:36