This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Re: this.type strangeness

No replies
Seth Tisue
Joined: 2008-12-16,
User offline. Last seen 34 weeks 3 days ago.

>>>>> "Stepan" == Stepan Koltsov writes:

Stepan> class A { def b(): this.type = { val r = this; r } }
Stepan> Fails to compile: found : r.type (with underlying type A)
Stepan> required: A.this.type. Is it a bug, or I don't understand how
Stepan> this.type work?

It's not a bug. foo.type means something much more specific than "the
type of foo". It means "the *singleton* type of foo". (I was hazy on
what exactly singleton types were, but I just spent an hour reading
about it and I think I understand now...)

The type of "this" is just A, not the singleton type this.type,
according to SLS 6.5. So the inferred type of r is also A. You don't
get a singleton type unless you specifically ask for one.

Programming in Scala, section 27.6: "Usually [singleton] types are too
specific to be useful, which is why the compiler is reluctant to insert
them automatically."

Here's an example of when singleton types are useful:
http://scalada.blogspot.com/2008/02/thistype-for-chaining-method-calls.html
The cake pattern paper (Scalable Component Abstractions) has an example
of how they are used in the architecture of the Scala compiler itself.

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland