-->

相当于斯卡拉Ruby的#tap方法[复制]相当于斯卡拉Ruby的#tap方法[复制](Equival

2019-05-12 09:21发布

这个问题已经在这里有一个答案:

  • 如何使返回值在斯卡拉登录时 6个回答

Ruby有一个方法,使我们能够观察值的管道,而无需修改基本价值:

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

有没有在斯卡拉这样的方法? 我相信,这就是所谓的红隼Combinator的,但不能肯定。

Answer 1:

这是在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"
})


文章来源: Equivalent to Ruby's #tap method in Scala [duplicate]