提问人:Matei 提问时间:3/30/2023 更新时间:3/31/2023 访问量:74
在 Scala 中将成员函数调用与其他函数调用相结合的惯用方式是什么?[复制]
What is the idiomatic way to combine member function calls with other function calls in Scala? [duplicate]
问:
假设我们在 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)
答:
2赞
Dmytro Mitin
3/31/2023
#1
使用可以重写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-pipe-tap-chaining-operations/
评论
pipe
pipe
scalacOptions += "-Yimports:java.lang,scala,scala.Predef,scala.util.chaining"