title: elementary operator overloading in Groovy
body: <p>I am new in Groovy and I have done only C# and C++ before, so I have some problems with getting used to Java and especially to Groovy that we use for our project. So the question concerns Groovy.</p>
  
  <p>I am trying to:</p>
  
  <ul>
  <li>create a new class X:</li>
  </ul>
  
  <pre class="lang-groovy prettyprint-override"><code>class X {
          double val
  }
  </code></pre>
  
  <ul>
  <li>Overload elementary operators (+,-,*,/,** etc) for variables of class X</li>
  </ul>
  
  <p>The problem is:
  - In Groovy I can overload operators for class X including one attribute - value (that is double)  </p>
  
  <pre><code>X plus(X obj){
    X newobj = new X(this.val + obj.val)
    return newobj
  }
  </code></pre>
  
  <p>and</p>
  
  <pre><code>X plus(double obj){
    X newobj = new X(this.val + obj)
    return newobj
  }
  </code></pre>
  
  <p>But how do I do if the double object is on the first place (left hand side) in addition? Like:</p>
  
  <p><code>double a
  X b
  X result = a + b
  // it will not work because operator + of a is not overloaded to provide addition of b
  </code></p>
  
  <p>Do I need to overload something like this but for double operators?:</p>
  
  <pre><code>ArrayList.metaClass.plus &lt;&lt; {Collection b -&gt; 
      [delegate, b].transpose().collect{x, y -&gt; x+y}
  }
  </code></pre>
  
  <p>as was said in 
  <a href="https://stackoverflow.com/questions/4443557/overloading-operator-for-arrays-in-groovy">Overloading + operator for arrays in groovy</a></p>
  
  <p>Maybe there is a way to add a method as closure accessing metaclass?</p>
  
  <p>Unfortunately the example with arrays is the closest answer that I have found in the internet. Hope there is a way!</p>