Explain "this.type" as the return type of various API methods

I look like the source code of a Promise[T]tag from a package scala.concurrent. So, here is a method declaration where I need your help in one place:

trait Promise[T] {
 ....
 def complete(result: Try[T]): this.type =
 if (tryComplete(result)) this else throw new IllegalStateException("Promise already completed.")
 ....
}

I do not understand how to interpret it this.typeas a return type of a method complete. Why can't a simple return type be Promise[T]?

Sorry if my question seems too simple for someone, I'm just studying this stuff.

+4
source share
2 answers

this.type required in a path dependent context:

scala> class A { class B; def f(b: B): A = this }
defined class A

scala> val a1 = new A; val b1 = new a1.B; val a2 = new A
a1: A = A@721f1edb
b1: a1.B = A$B@5922f665
a2: A = A@65e8e9b

scala> a1.f(b1)
res6: A = A@721f1edb

scala> a2.f(b1)
<console>:12: error: type mismatch;
 found   : a1.B
 required: a2.B
              a2.f(b1)
                   ^

, , . , new a1.B a1.B, B. :

scala> a1.f(b1).f(b1)
<console>:11: error: type mismatch;
 found   : a1.B
 required: _2.B where val _2: A
              a1.f(b1).f(b1)
                         ^

, f A, . this.type , :

scala> class A { class B; def f(b: B): this.type = this }
defined class A

scala> val a1 = new A; val b1 = new a1.B; val a2 = new A
a1: A = A@60c40d9c
b1: a1.B = A$B@6759ae65
a2: A = A@30c89de5

scala> a1.f(b1).f(b1)
res10: a1.type = A@60c40d9c
+2

, .

trait Foo[A] {
  def foo: Foo[A] = this
}

trait Bar[A] extends Foo[A]

scala> (new Foo[Int]{}).foo
res0: Foo[Int] = $anon$1@7f0aa670

scala> (new Bar[Int]{}).foo
res1: Foo[Int] = $anon$1@4ee2dd22

, foo a Foo[Int] , , "hardcoded" Foo[T].

trait Foo[A] {
  def foo: this.type = this
}

trait Bar[A] extends Foo[A]

, foo on:

scala> (new Foo[Int]{}).foo
res2: Foo[Int] = $anon$1@1391e025

scala> (new Bar[Int]{}).foo
res3: Bar[Int] = $anon$1@4142991e
+2

All Articles