scalatraitsself-typef-bounded-polymorphismreturn-current-type

How to let trait use `this` constructor in scala?


[edit update] this is a proper statment of my problem.

I hope to call the constructor inside a trait. But it seems I have to use apply function. does it exist usage like new this()?

Like the code below. It throws type mismatch. I hope to add constraint of constructor, or I have to use apply function.

  trait B { this:C =>
    def values:Seq[Int]
    def apply(ints:Seq[Int]):this.type
    def hello:this.type = apply( values map (_ + 1) )
  }

  trait C

  class A(val v:Seq[Int]) extends C with B{
    override def values: Seq[Int] = v

    override def apply(ints: Seq[Int]): A.this.type = new A(ints)
  }

Solution

  • this.type is the type of this specific instance. So you can write

    override def hello = this
    

    but you can't write

    override def hello = new A()
    

    since A is a supertype of this.type.

    Probably you wanted

    trait B { this: C =>
      type This <: B /*or B with C*/
      def hello: This
    }
    
    trait C
    
    class A extends C with B {
      type This = A
      override def hello = new A()
    }
    

    Or maybe even

    trait B { self: C =>
      type This >: self.type <: B with C { type This = self.This }
      def hello: This
    }
    

    Returning the "Current" Type in Scala https://tpolecat.github.io/2015/04/29/f-bounds.html