Skip to content

Instantly share code, notes, and snippets.

@sadache
Created October 1, 2010 19:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sadache/606744 to your computer and use it in GitHub Desktop.
Save sadache/606744 to your computer and use it in GitHub Desktop.
def substract(i:Int)=extension{
//owner represents the object you are extending
owner:Int =>
{
owner-i
}
}
//operator tild ~ instead of . for extensions
1~substract(2)~substract(1)~substract(1)
//implementation of extension methods in scala:
object ExtensionFunctions{
case class ExtensionFunction[A,R](f:Function[A,R]) extends Function[A,R]{override def apply(a:A)=f(a)}
def extension[A,R](f:A=>R)=ExtensionFunction(f)
implicit def anythingIsExtensible[A](a:A):ExtensionsOn[A]= ExtensionsOn(a)
case class ExtensionsOn[A](a:A){
//adding this generic operator on type Any would ?remove? the overhead of doing implicit conversions here
def ~[R] (f:ExtensionFunction[A,R]):R = f(a)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment