在Scala中,将成员函数调用与其他函数调用结合起来的惯用方法是什么?



假设我们在Scala中有一个对象(例如一个列表),并且我们想用对象成员函数对用户定义函数进行排序,例如:

g(l.map(f)
.foldRight(...))
.map(h)

如果函数序列比较大,代码就会变得有点混乱。有没有更好的方法来编写这样的代码?比如:

l.map(f)
.foldRight(...)
.call(g)   // call would simply call function g on the resulting object
.map(h)

使用scala.util.chaining._可以重写

trait A
trait B
trait C
trait D
trait E
val l:  List[A]      = ???
val f:  A => B       = ???
val z:  C            = ???
val op: (B, C) => C  = ???
val g:  C => List[D] = ???
val h:  D => E       = ???
g(l.map(f)
.foldRight(z)(op))
.map(h)

import scala.util.chaining._
l.map(f)
.foldRight(z)(op)
.pipe(g)
.map(h)

https://github.com/scala/scala/blob/v2.13.10/src/library/scala/util/ChainingOps.scala

https://blog.knoldus.com/new-chaining-operations-in-scala-2-13/

https://alvinalexander.com/scala/scala - 2.13 -管-利用-链接- operations/

最新更新