title: Scala factory for generic types using the apply method?
body: <p>Suppose that I have the following trait that defines an interface and takes a couple of type parameters...</p>
  
  <pre><code>trait Foo[A, B] {
  
      // implementation details not important
  
  }
  </code></pre>
  
  <p>I want to use the companion object as a factory for concrete implementations of the trait.  I also want to force users to use the <code>Foo</code> interface instead of sub-classing So I hide the concrete implementations in the companion object like so:</p>
  
  <pre><code>object Foo {
  
    def apply[A, B](thing: Thing): Foo[A, B] = {
      ???
    }
  
    private case class FooImpl[A1, B1](thing: Thing) extends Foo[A1, B1]
  
    private case class AnotherFooImpl[A2, B1](thing: Thing) extends Foo[A2, B1]
  
  }
  </code></pre>
  
  <p>I want to be able to use the factory as follows:</p>
  
  <pre><code>val foo = Foo[A1, B1](thing)  // should be an instance of FooImpl
  
  val anotherFoo = Foo[A2, B1](thing)  // should be an instance of AnotherFooImpl
  </code></pre>
  
  <p>How do I implement the <code>apply</code> method to make this happen? This <a href="https://stackoverflow.com/questions/30926958/scala-factory-method-with-generics">SO post</a> seems close to the mark.</p>