title: Scala: Implicit Conversion From Generic Type to Second Generic Type
body: <p>Say I have two sets of classes and the first set inherits from Foo and the second set inherits from Bar.</p>
  
  <pre><code>class Foo
  class Baz extends Foo
  class Bar
  class Qux extends Bar
  </code></pre>
  
  <p>I want to make a generic implicit conversion function that converts any Foo to Bar given there is an implicit converter type in scope.</p>
  
  <pre><code>trait Converter[A &lt;: Foo, B &lt;: Bar] {
    def convert(a : A) : B
  }
  
  implicit object BazToQuxConverter extends Converter[Baz, Qux] {
    def convert(a : Baz) : Qux = new Qux
  }
  
  implicit def FooToBar[A &lt;: Foo, B &lt;: Bar](a : A)(implicit converter : Converter[A, B]) : B = converter.convert(a)
  </code></pre>
  
  <p>Unfortunately, this doesn't seem to work as I would expect it to. When I plug in the following lines to the REPL:</p>
  
  <pre><code>val a : Baz = new Baz
  val b : Qux = a
  </code></pre>
  
  <p>...I get the following error:</p>
  
  <pre><code>&lt;console&gt;:17: error: type mismatch;
   found   : Baz
   required: Qux
         val b : Qux = a
                       ^
  </code></pre>
  
  <p>Is there any way to get this to work? The closest I've been able to come is the following:</p>
  
  <pre><code>implicit def BadFooToBar[A &lt;: Foo, B &lt;: Bar](a : A)(implicit converter : Converter[A, _]) : B = converter.convert(a).asInstanceOf[B]
  </code></pre>
  
  <p>This does work for my previous example, but it's not very type-safe.</p>
  
  <pre><code>class Qax extends Bar
  val a : Baz = new Baz
  val b : Qax = a
  </code></pre>
  
  <p>This will compile just fine, but it will blow up at run-time because a <code>Qux</code> (the result of <code>converter.convert(a)</code>) can't be cast to <code>Qax</code> (<code>asInstanceOf[Qax]</code>). Ideally, I want it so that the above line will be caught at compile time since there isn't any <code>Converter[Bax,Qax]</code> in scope.</p>