【问题标题】:Equivalent to Ruby's #tap method in Scala [duplicate]等效于 Scala 中 Ruby 的 #tap 方法 [重复]
【发布时间】:2013-05-24 19:10:13
【问题描述】:

Ruby 有一个方法可以让我们观察值的管道,而无需修改底层值:

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

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

【问题讨论】:

  • 你谷歌 scala kestrel 组合器了吗?这有帮助吗? stackoverflow.com/a/9673294/1339987
  • @djechlin 不,在“模拟一只知更鸟”中搜索并写了 Kestrel,但忘了谷歌,呃。正是我想要的。
  • also whole blogpost dedicated to the use of the kestrel in scala。不幸的是,scala 没有这种开箱即用的东西。
  • @FrançoisBeausoleil 我听不懂你的讽刺 - 真的有帮助吗?
  • 作为参考,2.10 中使用 Ruby 表示法的惯用版本为 implicit class TapAnyone[A](val value: A) extends AnyVal { def tap[B](f: A => B) = { f(value); value } }

标签: scala combinatory-logic


【解决方案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"
})

【讨论】:

  • 如果你添加相同版本的隐式类会很好,导致隐式转换称为tap[a]和Tap类中的方法tap,可能有点晦涩
  • 对于 Scala 2.13+,请参阅:stackoverflow.com/a/54610963/637754
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-20
  • 1970-01-01
  • 2021-08-16
  • 2011-10-13
  • 1970-01-01
  • 1970-01-01
  • 2013-11-30
相关资源
最近更新 更多