Java Reference
In-Depth Information
class as desired, and the resulting members will be part of any instantiated object. Here's
how to add several mathematical operations to Complex :
Complex. metaClass .plus = { Complex c -> delegate.add c }
Complex. metaClass .minus = { Complex c -> delegate.subtract c }
Complex. metaClass .div = { Complex c -> delegate.divide c }
Complex. metaClass .power = { Complex c -> delegate.pow c }
Complex. metaClass .negative = { delegate.negate() }
That takes care of the + , - , / , ** , and negation operators, respectively. In each case, the
relevant method is defined on the metaclass by setting it equal to a closure. The associated
closure takes a Complex argument (in the case of binary operators) and invokes the de-
sired existing method on the closure's delegate, passing along the argument.
Closure Delegates
Every closure has a delegate property. By default the delegate points to the object that
the closure was invoked on.
After adding those methods to the metaclass, the operators can be used in the Groovy
script:
assert new Complex(3.0, 8.0) == first + second
assert new Complex(1.0, 2.0) == second - first
assert new Complex(0.5862068965517241, 0.03448275862068969) ==
first / second
assert new Complex(-0.007563724861696302, 0.01786136835085382) ==
first ** second
assert new Complex(-1.0, -3.0) == -first
To complete this part of the story I want to demonstrate the famous equation known as
Euler's identity, [ 9 ] which is expressed as
9 Leonhard Euler (1707 - 1783) was one of the most brilliant mathematicians of all time. His work spanned virtually
every field of math and science, and his collected works filled between 60 and 80 quarto volumes. The transcend-
ental number e is named after him.
e =-1
 
Search WWH ::




Custom Search