Skip to content

Instantly share code, notes, and snippets.

@KirinDave
Created February 25, 2011 19:22
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KirinDave/844334 to your computer and use it in GitHub Desktop.
Save KirinDave/844334 to your computer and use it in GitHub Desktop.
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