Skip to content

Instantly share code, notes, and snippets.

@davidallsopp
Created November 27, 2014 12:06
Show Gist options
  • Select an option

  • Save davidallsopp/d2a597fea1c7ff112eb9 to your computer and use it in GitHub Desktop.

Select an option

Save davidallsopp/d2a597fea1c7ff112eb9 to your computer and use it in GitHub Desktop.
Utilities to enable side-effects (logging, updating mutable counters etc) in the middle of a functional (map/flatmap/filter etc) chain of calls.
/**
* Enrich any object so we can run side-effects (such as logging) without needing temporary variables.
*
* <p>Adapted from http://naildrivin5.com/blog/2012/06/22/tap-versus-intermediate-variables.html
*
* <pre>
* "foobar".tap { s => if (s.contains("bar")) println("Got bar") }.toUpperCase()
* </pre>
*/
implicit class Tap[A](obj: A) {
def tap(code: A => Unit): A = {
code(obj)
obj
}
}
/**
* Enrich a Try object so we can run side-effects (such as logging) without needing temporary variables
* and explicit pattern matching, especially since Try does not have a fold() method in Scala 2.10.
*
* <pre>
* Try("ok").tap(s => println(s), e => throw new Exception(e)).map(_.toUpperCase)
* </pre>
*/
implicit class TryTap[A](obj: Try[A]) {
def tap(succ: A => Unit, fail: Throwable => Unit): Try[A] = {
obj match {
case Success(a) => succ(a)
case Failure(e) => fail(e)
}
obj
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment