Skip to content

Instantly share code, notes, and snippets.

@tobym
Created July 29, 2011 20:13
Show Gist options
  • Save tobym/1114627 to your computer and use it in GitHub Desktop.
Save tobym/1114627 to your computer and use it in GitHub Desktop.
object Functional {
/*
* Adds the k-combinator to an object. This lets you apply a function to the
* calling object; useful for accessing entire collections in the middle of
* a series of transformations. This lets you do horrible, side-effecting
* things to mutable collections, so try to avoid that.
*
* Example:
*
* List(1, 2, 3).map(_ * 2).k{ x => println(x) }.filter(_ > 4)
*
* Prints "List(2, 4, 6)" and returns List(6)
*/
class KCombinator[T](x: T) {
def k(f: (T) => Unit): T = {
f(x)
x
}
}
implicit def addKCombinator[T](x: T) = new KCombinator[T](x)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment