问题
Ruby has a method that allows us to observe a pipeline of values, without modifying the underlying value:
# Ruby
list.tap{|o| p o}.map{|o| 2*o}.tap{|o| p o}
Is there such a method in Scala? I believe this is called a Kestrel Combinator, but can't be sure.
回答1:
Here is one implementation on github: https://gist.github.com/akiellor/1308190
Reproducing here:
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"
})
来源:https://stackoverflow.com/questions/16742060/equivalent-to-rubys-tap-method-in-scala