3

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}

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

sawa
  • 165,429
  • 45
  • 277
  • 381
François Beausoleil
  • 16,265
  • 11
  • 67
  • 90
  • 2
    Did you google scala kestrel combinator? Does this help? http://stackoverflow.com/a/9673294/1339987 – djechlin May 24 '13 at 19:12
  • @djechlin No, searched in "To mock a mockingbird" and wrote Kestrel, but forgot to Google, duh. Exactly what I was looking for. – François Beausoleil May 24 '13 at 19:13
  • There is [also whole blogpost dedicated to the use of the kestrel in scala](http://debasishg.blogspot.ru/2009/09/side-effects-with-kestrel-in-scala.html). Unfortunately, scala has no such thing out-of-the-box. – om-nom-nom May 24 '13 at 19:14
  • @FrançoisBeausoleil I can't follow your sarcasm - *did* that actually help? – djechlin May 24 '13 at 19:31
  • 1
    For reference, the idiomatic version in 2.10 using the Ruby notation would be `implicit class TapAnyone[A](val value: A) extends AnyVal { def tap[B](f: A => B) = { f(value); value } }` – Rex Kerr May 24 '13 at 20:57
  • @djechlin Sorry, I wasn't even trying to be sarcastic. I tried to explain that I looked in my book, and forgot to Google before coming here. Sorry for the confusion. Yes, your reference did help. – François Beausoleil May 25 '13 at 20:19

1 Answers1

4

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"
})
djechlin
  • 59,258
  • 35
  • 162
  • 290
  • That would be good if you add same version with implicit class, cause implicit conversion called tap[a] and method tap in class Tap, can be a bit obscure – 4lex1v May 24 '13 at 20:36
  • 1
    For Scala 2.13+ see: https://stackoverflow.com/a/54610963/637754 – Governa Oct 19 '19 at 01:49