Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
586 views
in Technique[技术] by (71.8m points)

scala - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...