title: Scala Builder Pattern: illegal cyclic reference involving type T
body: <p>I'm trying to write some generic builders for my User class hierarchy.
  I have a trait, UserBuilder and each "with" method in the trait has to return the same type as the current class. So if I'm inside the ComplexUserBuilder, the withId method should return a ComplexUserBuilder and not a UserBuilder.</p>
  
  <p>But I'm getting </p>
  
  <blockquote>
    <p>illegal cyclic reference involving type T</p>
  </blockquote>
  
  <p>Is there a way to workaround this?</p>
  
  <p>Here is my code:</p>
  
  <pre><code>trait UserBuilder[T &gt;: UserBuilder[T]] {
  
    var id: String = ""
  
    def withId(id: String): T = {
      this.id = id
      return this
    }
  }
  
  class ComplexUserBuilder extends UserBuilder[ComplexUserBuilder] {
  
    var username: String = ""
  
    def withUsername(username: String): ComplexUserBuilder = {
      this.username = username
      return this
    }
  
    def build = new ComplexUser(id, username)
  }
  </code></pre>
  
  <p>By the way, if I replace <code>trait UserBuilder[T &gt;: UserBuilder[T]]</code> with <code>trait UserBuilder[T &gt;: UserBuilder[_]]</code> I get:</p>
  
  <blockquote>
    <p>type arguments [model.ComplexUserBuilder] do not conform to trait UserBuilder's type parameter bounds [T >: model.UserBuilder[_]]</p>
  </blockquote>
  
  <p>Update:</p>
  
  <pre><code>trait UserBuilder[T &gt;: UserBuilder[T]]
  </code></pre>
  
  <p>should be (as GClaramunt suggested)</p>
  
  <pre><code>trait UserBuilder[T &lt;: UserBuilder[T]]
  </code></pre>
  
  <p>but now there is an ugly cast as the return type</p>