Sick Things in Scala: Implicit Conversions of Functions
September 11th, 2009 — — Permalink
I've been having a play with seeing just how far Scala can be bent before it is broken.
My latest finding is that you can implicitly convert functions to other types.
For example:
object Sickness {
class WrappedFunction
implicit def functionWrapper(f : => Unit) : WrappedFunction = {
System.out.println("Going to call the function")
f
// Essential! otherwise the conversion happens infinitely
new WrappedFunction
}
// Have to specify the type so that the function is converted
def wrapMyFunction : WrappedFunction = {
System.out.println("Function called!")
}
// And to demonstrate...
def main(args: Array[String]) {
wrapMyFunction
wrapMyFunction
/
* The above outputs:
* Going to call the function
* Function called!
* Going to call the function
* Function called!
/
}
}
This allows for some pretty funky meta-programming-like gymnastics.
Now to find something useful for this :)
