Difference between this and self in self-type annotations?

后端 未结 2 1469
攒了一身酷
攒了一身酷 2020-11-27 09:27

In various Scala literature I see some self-type annotations using \"this\" and others using \"self\":

trait A { this: B => ... }
trait A { self: B =>          


        
2条回答
  •  悲&欢浪女
    2020-11-27 10:16

    There is a difference in that this always refers to the object defined by the innermost template.

    The expression this can appear in the statement part of a template or compound type. It stands for the object being defined by the innermost template or compound type enclosing the reference. If this is a compound type, the type of this is that compound type. If it is a template of a class or object definition with simple name C, the type of this is the same as the type of C.this. (Scala Ref. §6.5)

    So, if you call your self-type foo, you could still refer to it as this (unless, of course, you are in an inner template in which case this will refer to the object defined by it – and unless you don’t give the inner template’s self-type the same name) but obviously not the other way round.

提交回复
热议问题