Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit self-references with no type / difference with ''this''

I understand the use for explicitly typed self-references:

trait T {
  self : T2 =>
  ...
}

In the body, self is an alias for this but has the more precise type T with T2.

Now, I've seen this in code:

trait T {
  self =>
  ...
}

That is, an explicit self reference with no additional type information. In this configuration, is there any situation in which self is not just an alias for this?

like image 514
Philippe Avatar asked Nov 09 '11 23:11

Philippe


2 Answers

It is an alias for this.

Your first example is useful for ensuring that the trait has been mixed in to an appropriate type, and makes those methods available.

The second example is useful when you have inner classes with naming conflicts, to make the outer scope visible. For example:

trait U {
  self =>
  val name = "outer"
  val b = new AnyRef {
    val name = "inner"
    println(name)
    println(this.name)
    println(self.name)
  }
}

Then new AnyRef with U prints

inner
inner
outer

"self" is not a special keyword - you can use "bananas =>" or whatever you like, but it's often used by convention.

This crops up quite a bit in Swing, where you make a lot on inner classes (textboxes within scrollpanes, etc), which usually have many methods with the same names as the outer classes.

like image 60
Luigi Plinge Avatar answered Nov 19 '22 21:11

Luigi Plinge


In that case self is a another way of saying this.

If you happen to have an inner class, however, this inside the inner class would be the inner class, and self would be the container class.

That's the only difference AFAIK

like image 10
Pablo Fernandez Avatar answered Nov 19 '22 21:11

Pablo Fernandez