In Groovy everything is Object, even numbers
assert 1.getClass() == Integer
In Groovy you can override existing method in an existing class in runtime
Integer.metaClass.or = { right -> println "$delegate or $right" }
Now we can call or operator on any number using pipe (|)
1.or("hello") // prints: 1 or hello
1 | "hello" // prints: 1 or hello
So far so good. Now let’s try to or an Integer with an Integer
2.or(3) // nothing happens
2 | 3 // nothing happens
This leads us to my questions:
- Why nothing happens?
- Is this an optimization bug?
- How to make it work for any type?
It’s probably choosing an already existing
ormethod that takes an integer, rather than your more generic Object version.Does it work if you do:
Not at a computer at the moment though, so can’t validate this :-/