Created
February 25, 2011 19:22
-
-
Save KirinDave/844334 to your computer and use it in GitHub Desktop.
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
package com.banksimple.util | |
private[util] final class Effectful[T](val origin: T) { | |
/** | |
* A special case of doto, andAlso is useful for | |
* quick logging or output tasks. Similar in use | |
* to doto, but only takes one function. | |
* */ | |
def andAlso(x: T => Unit): T = { x(origin) ; origin } | |
/** | |
* Useful if you want to cause side effects | |
* upon the completion of a value, but then | |
* return the value. This frequently occurs | |
* in server-oriented code where logging and | |
* metrics events need to be created. | |
* */ | |
def andThen(x: => Unit): T = { x ; origin } | |
/** | |
* Copying Clojure's (doto JavaObject ...) | |
* | |
* Takes an object and causes side effects on it, then | |
* returns the object. Useful with old-style mutable | |
* java objects that require lots of setters to be | |
* called in sequence. Calls can be nested. | |
* | |
* Example usage: | |
* {{{ | |
* (new Id).doto( | |
* _.setType(Id.SSN), | |
* _.setValue("123-456-7890")) | |
* }}} | |
*/ | |
def doto(mutators: Function1[T,Unit]*): T = { | |
for( f <- mutators ) { f(origin) } | |
origin | |
} | |
} | |
trait EffectfulImplicits { | |
implicit def any2Effectful[T](x: T): Effectful[T] = new Effectful(x) | |
} | |
object Effectful extends EffectfulImplicits |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment