Self argument in Scala

前端 未结 1 1891
遇见更好的自我
遇见更好的自我 2021-01-05 22:50

This example is from one of the Scala books:

trait IO { self =>
  def run: Unit
  def ++(io: IO): IO = new IO {
    def run = { self.run; io.run }
  } 
}
         


        
相关标签:
1条回答
  • 2021-01-05 23:23

    self is just an alias to this in the object in which it is declared, and it can be any valid identifier (but not this, otherwise no alias is made). So self can be used to reference this from an outer object from within an inner object, where this would otherwise mean something different. Perhaps this example will clear things up:

    trait Outer { self =>
        val a = 1
    
        def thisA = this.a // this refers to an instance of Outer
        def selfA = self.a // self is just an alias for this (instance of Outer)
    
        object Inner {
            val a = 2
    
            def thisA = this.a // this refers to an instance of Inner (this object)
            def selfA = self.a // self is still an alias for this (instance of Outer)
        }
    
    }
    
    object Outer extends Outer
    
    Outer.a // 1
    Outer.thisA // 1
    Outer.selfA // 1
    
    Outer.Inner.a // 2
    Outer.Inner.thisA // 2
    Outer.Inner.selfA // 1 *** From `Outer` 
    
    0 讨论(0)
提交回复
热议问题