相当于Ruby';Scala中的s#tap方法

相当于Ruby';Scala中的s#tap方法,scala,combinatory-logic,Scala,Combinatory Logic,Ruby有一种方法,允许我们观察一系列值,而无需修改底层值: # Ruby list.tap{|o| p o}.map{|o| 2*o}.tap{|o| p o} Scala中有这样的方法吗?我相信这被称为Kestrel Combinator,但不能确定。这里是github上的一个实现: 在此复制: import collection.mutable.MutableList import Tap._ class Tap[A](any: A) { def tap(f: (A) =>

Ruby有一种方法,允许我们观察一系列值,而无需修改底层值:

# Ruby
list.tap{|o| p o}.map{|o| 2*o}.tap{|o| p o}

Scala中有这样的方法吗?我相信这被称为Kestrel Combinator,但不能确定。

这里是github上的一个实现:

在此复制:

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 kestrel combinator吗?这有用吗@杰克林没有,他在“模仿一只知更鸟”中搜索,并写了《红隼》,但忘了谷歌。正是我要找的,有。不幸的是,scala没有这种现成的东西。@Françoisbausoleil我听不懂你的讽刺——这真的有用吗?作为参考,2.10中使用Ruby表示法的惯用版本是
隐式类TapAnywhere[A](val-value:A)扩展AnyVal{def-tap[B](f:A=>B)={f(value);value}
如果添加与隐式类相同的版本,这将是一件好事,因为称为tap[a]的隐式转换和类tap中的方法tap对于Scala 2.13+来说可能有点模糊,请参见: