5

Possible Duplicate:
What is the difference between scala self-types and trait subclasses?

I understand a self-annotation as a promise to the compiler, where the programmer manifests that a trait will be mixin with the annotated one. For example:

scala> trait X
defined trait X

scala> trait Y { this: X => }
defined trait Y

scala> new Y {}
<console>:10: error: illegal inheritance;
self-type Y does not conform to Y's selftype Y with X
              new Y {}
                  ^

scala> new Y with X {}
res1: Y with X = $anon$1@1125a40

In the previous example, the third expression failed because we did not set a valid X to the new instance. Obviously, the last one works nice. So far, so good. And now, let's see another example which involves an object.

scala> object Z { this: X => }
defined module Z

I understand the object is being instantiated failing with the X promise (we are creating an instance now with a future promise!), as represented in the next lines, where the traits have been slightly modified:

scala> trait X { class X1 }
defined trait X

scala> trait Y { this: X => new X1 }
defined trait Y

scala> object Z { this: X => new X1 }
<console>:8: error: not found: type X1
       object Z { this: X => new X1 }
                                 ^

So, what does the object self-annotation imply?

Community
  • 1
  • 1
neutropolis
  • 1,884
  • 15
  • 34

1 Answers1

3

In fact, you can do the same thing with classes - add a self-type which is not inherited, but you won't be able to instantiate such a class.

Allowing singleton objects to have self types does not invalidate programs in any way - you simply won't be able to call any of the methods of the self-type (or instantiate its inner classes) from within the singleton object, because it didn't inherit the self-type.

Nevertheless, it may be a bug, you may wish to file a bug.

axel22
  • 32,045
  • 9
  • 125
  • 137
  • I think that in the class case, for example: "class A { this: X => new X1 }" you can play with "new A with X", so it has sense, but I cannot find any situation where one could need the self annotation in an object. – neutropolis Jun 28 '12 at 11:31
  • True, for objects and final classes, it makes no sense that I can see. – axel22 Jun 28 '12 at 11:34
  • Mind you, I think objects can actually be overridden if they are members of a trait or class. – Daniel C. Sobral Jun 28 '12 at 19:23
  • Can they - aren't they final members? http://pastebin.com/yvNU9QrB – axel22 Jun 28 '12 at 19:37