Difference between this and self in self-type annotations?

后端 未结 2 1452
攒了一身酷
攒了一身酷 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:21

    All three forms are valid, and have the effect that B is assumed as the type of this in class A.

    The first two variants

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

    introduce self (respectively, foo) as an alias for this in trait A. This is useful for accessing the this reference from an inner class. I.e. you could then use self instead of A.this when accessing the this reference of the trait A from a class nested within it. Example:

    class MyFrame extends JFrame { frame =>    
      getContentPane().add( new JButton( "Hide" ) {
        addActionListener( new ActionListener {
          def actionPerformed( e: ActionEvent ) {
            // this.setVisible( false ) --> shadowed by JButton!
            frame.setVisible( false )
          }
        })
      })
    }
    

    The third variant,

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

    does not introduce an alias for this; it just sets the self type.

提交回复
热议问题