title: Coding style for overloading operators
body: <p>Suppose that I have a class called <code>Rational</code> which represents rational numbers "purely", i.e it maintains the representation of a/b as <code>(a, b)</code> and implements the usual operators <code>+, -, *, /</code> and others to work on those tuples, instead of evaluating the actual fractions on every operation.</p>
  
  <p>Suppose now that I want to define what happens if I add a <code>Rational</code> instance to an <code>Int</code>, in addition to the already defined behavior for <code>Rational</code> added to <code>Rational</code>. Then, of course, I might end up wanting to add <code>Rational</code> to <code>Double</code>, or to <code>Float</code>, <code>BigInt</code> other numeric types... </p>
  
  <h2>Approach #1: Provide several implementations of <code>+(Rational, _)</code>:</h2>
  
  <pre><code>def + (that:Rational):Rational  = {
      require(that != null, "Rational + Rational: Provided null argument.")
      new Rational(this.numer * that.denom + that.numer * this.denom, this.denom * that.denom)
  }
  
  def + (that:Int): Rational = this + new Rational(that, 1) // Constructor takes (numer, denom) pair
  
  def + (that:BigInt): Rational = ....
  .
  .
  .
  </code></pre>
  
  <h2>Approach #2: Pattern match on <code>Any</code>:</h2>
  
  <pre><code>def + (that:Any):Rational  = {
      require(that != null, "+(Rational, Any): Provided null argument.")
      that match {
          case that:Rational =&gt; new Rational(this.numer * that.denom + that.numer * this.denom, this.denom * that.denom)
          case that:Int | BigInt =&gt; new Rational(this.numer + that * this.denom, this.denom) // a /b + c = (a + cb)/b
          case that:Double =&gt; ....
          .
          .
          .
          case _ =&gt; throw new UnsupportedOperationException("+(Rational, Any): Unsupported operand.")
       }
  }
  </code></pre>
  
  <p>One benefit I'm seeing from the pattern matching approach is saving in terms of actual source code lines, but perhaps with a decrease of readability. Perhaps more crucially, I have control over what I do when I'm provided with a type I haven't defined behavior of <code>+</code> for. I'm not certain how that could be attained via the first approach, perhaps by adding an overloading for <code>Any</code> underneath all the others? Either way, it sounds dangerous. </p>
  
  <p>Ideas on whether one should opt for the first or second approach? Are there any safety issues I'm not seeing? Am I opening myself to <code>ClassCastException</code>s or other kinds of exceptions?</p>