Equivalent to Ruby’s #tap method in Scala [duplicate]

Here is one implementation on github: https://gist.github.com/akiellor/1308190

Reproducing here:

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

Leave a Comment