Equivalent to Ruby's #tap method in Scala [duplicate]

心已入冬 提交于 2019-11-26 14:50:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!