title: Defining a scala trait def that returns a concrete sub type instance
body: <p>I am attempting to define a base trait used for a simple CRUD system.  However, I need the base trait to support a "copyWithId" def (since the Scala case class magic for copy is not available).  The best approach I have found so far is:</p>
  
  <pre><code>trait Identifiable[ID, T] {
    def id: Option[ID]
    def copyWithId(id: Option[ID]): T
  }
  
  case class TestNamedIdentity(id: Option[Int], name: String) 
      extends Identifiable[Int, TestNamedIdentity] {
  
    def copyWithId(id: Option[Int]): TestNamedIdentity = {
      copy(id = id)
    }
  }
  </code></pre>
  
  <p>This works but looks a bit clunky because it requires all the concrete instances to extend with ID and Self.  I'd like to write something like the following:</p>
  
  <pre><code>trait Identifiable[ID] {
    this:X =&gt;
    def copyWithId(id: Option[ID]): X
    def id: Option[ID]
  }
  </code></pre>
  
  <p>Using some form of self-reference to the concrete class.  Any way to make this work?</p>
  
  <p><strong>Update: With use case below</strong></p>
  
  <p>The idea is to use it in code like</p>
  
  <pre><code>abstract class SomeClass[A &lt;: IdentifiableEntity[ID], ID] {
    def someFunc2: Option[ID]
    def someFunc(item: A): A = {
      item.copyWithId(someFunc2)
    }
  }
  </code></pre>
  
  <p>Using the solution from @jwvh requires "asInstanceOf" casting after the call.  Which for my use case works, but was hoping for a more elegant solution.</p>
  
  <pre><code>    item.copyWithId(someFunc2).asInstanceOf[A]
  </code></pre>