scala - 相当于Ruby在Scala中的#tap方法

标签 scala combinatory-logic

<分区>

Ruby 有一个方法可以让我们在不修改底层值的情况下观察值的管道:

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

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

最佳答案

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

关于scala - 相当于Ruby在Scala中的#tap方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16742060/

相关文章:

scala - Spark/Scala 拆分

sql - slick 3.1 中的多个聚合和子查询

haskell - 不返回组合表达式的所有可能的一步归约

haskell - 在 Haskell 中实现 Smullyan 的算术鸟

boolean - XOR 可以使用 SKI 组合器表示吗?

scala - 对于理解: how to run Futures sequentially

java - 如何获取 helper.form 中单选组中项目的 ID?

scala - Spark 编程: best way to organize context imports and others with multiple functions

haskell - 在 SKI 组合器中表达 XOR