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

前端 未结 2 1299
盖世英雄少女心
盖世英雄少女心 2020-11-30 04:24

I understand the use for explicitly typed self-references:

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

In the body, self is an alias f

2条回答
  •  眼角桃花
    2020-11-30 05:27

    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.

提交回复
热议问题