Created
November 27, 2014 12:06
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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