Meta programming: giving Integers a “fibonacci” property in Groovy

A tiling with squares whose sides are successi...
Image via Wikipedia

So, you just decide that each Integer should have an automatic property of knowing it’s Fibonacci number, well now your wish is granted:
Integer.metaClass.getFibonacci {
     fib = delegate
     def fibno = 1
     while (fib) {
         fibno += fibno
     return fibno

     Integer x = 25
     println x.fibonacci

I admit this is probably not the most useful additional property one could add to an integer and, of course, it is a function of an integer and not a property, but that was not my point…

%d bloggers like this: