scala - Explain "this.type" as a return type of various API methods -
i looking though source code of promise[t] trait scala.concurrent package. here method declaration need in 1 place:
trait promise[t] { .... def complete(result: try[t]): this.type = if (trycomplete(result)) else throw new illegalstateexception("promise completed.") .... } i not understand how interpret this.type complete method return type. why not simple return type promise[t] ?
sorry if question seem simple someone, learning stuff.
this.type necessary in path dependent context:
scala> class { class b; def f(b: b): = } defined class scala> val a1 = new a; val b1 = new a1.b; val a2 = new a1: = a@721f1edb b1: a1.b = a$b@5922f665 a2: = a@65e8e9b scala> a1.f(b1) res6: = a@721f1edb scala> a2.f(b1) <console>:12: error: type mismatch; found : a1.b required: a2.b a2.f(b1) ^ path dependent means compiler knows types belong together. in above example 1 can see new a1.b produces value of type a1.b , not b. however, not work:
scala> a1.f(b1).f(b1) <console>:11: error: type mismatch; found : a1.b required: _2.b val _2: a1.f(b1).f(b1) ^ the problem return type of f a, has no information anymore path dependent relationship. returning this.type instead tells compiler return type fulfills relationship:
scala> class { class b; def f(b: b): this.type = } defined class scala> val a1 = new a; val b1 = new a1.b; val a2 = new a1: = a@60c40d9c b1: a1.b = a$b@6759ae65 a2: = a@30c89de5 scala> a1.f(b1).f(b1) res10: a1.type = a@60c40d9c
Comments
Post a Comment