Clojure有"线程宏" ->
和->>
.我很确定在Scala代码中可以使用类似的构造来替换代码,例如:
var myObj = MyObject(x, y, z)
myObj = transform(myObj, abc)
myObj = transformMore(myObj, def)
myObj = transformYetMore(myObj, bar)
Run Code Online (Sandbox Code Playgroud)
我希望看到一个可行的例子,看看它是否看起来不错.我很确定你不需要在Scala案例中使用宏.
好问题!我可以想到几个这样的例子可以派上用场。举个例子,我正在处理一个数据集,我想在其上应用多个函数,同时将结果向前推进,如下所示:
val result: ResultSet = Functions.thread(inputSet)
.andThen(execute(_, executionContext))
.andThen(_.filter(_.nonEmpty))
.andThen(verifyData(_, verificationHelper))
.andThen(_.cache)
.andThen(saveSnapshot)
Run Code Online (Sandbox Code Playgroud)
要在没有线程的情况下编写相同的内容,您将需要嵌套调用或保存中间函数调用的结果。我更喜欢使用上述方法,因为它以更少的行数完成同样的事情,从而提高了代码的可维护性和可读性。
这是Functions
实现此目的的实用程序:
object Functions {
def thread[T](item: T) = new ThreadFunctor(item)
}
class ThreadFunctor[T](val item: T) {
def andThen(f: T => T): ThreadFunctor[T] = new ThreadFunctor(f(item))
}
object ThreadFunctor {
implicit def threadToItem[T](thread: ThreadFunctor[T]): T = thread.item
}
Run Code Online (Sandbox Code Playgroud)