<分区>
Ruby 有一个方法可以让我们在不修改底层值的情况下观察值的管道:
# Ruby
list.tap{|o| p o}.map{|o| 2*o}.tap{|o| p o}
Scala中有这样的方法吗?我相信这称为 Kestrel Combinator,但不能确定。
<分区>
Ruby 有一个方法可以让我们在不修改底层值的情况下观察值的管道:
# Ruby
list.tap{|o| p o}.map{|o| 2*o}.tap{|o| p o}
Scala中有这样的方法吗?我相信这称为 Kestrel Combinator,但不能确定。
最佳答案
这是 github 上的一个实现:https://gist.github.com/akiellor/1308190
转载于此:
import collection.mutable.MutableList
import Tap._
class Tap[A](any: A) {
def tap(f: (A) => Unit): A = {
f(any)
any
}
}
object Tap {
implicit def tap[A](toTap: A): Tap[A] = new Tap(toTap)
}
MutableList[String]().tap({m:MutableList[String] =>
m += "Blah"
})
MutableList[String]().tap(_ += "Blah")
MutableList[String]().tap({ l =>
l += "Blah"
l += "Blah"
})
关于scala - 相当于Ruby在Scala中的#tap方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16742060/