相当于 Scala 中 Ruby 的 #tap 方法 [英] Equivalent to Ruby's #tap method in Scala

查看:48
本文介绍了相当于 Scala 中 Ruby 的 #tap 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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}

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

Is there such a method in Scala? I believe this is called a Kestrel Combinator, but can't be sure.

推荐答案

这是 github 上的一个实现:https://gist.github.com/akiellor/1308190

Here is one implementation on 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 的 #tap 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆