Scala this aliasing and self type

后端 未结 1 632
無奈伤痛
無奈伤痛 2021-01-13 16:09

Is there any relationship between this aliasing and self type? Is this aliasing a special case of self type? In programm

相关标签:
1条回答
  • 2021-01-13 16:31

    You can have a self-type and this aliasing at the same time:

    abstract class Parser[+T] { p: SomeAssumedType => … }
    

    If you don’t include a type ascription, Scala will assume that the type of the variable is the type of the surrounding class, thus giving you a simple alias for this.

    If you keep the name this with the ascription, then Scala expects you to initialise this class in a way that the ascription can be fulfilled.

    As for the this aliasing. Here’s the situation in which this is needed:

    object OuterObject { outer =>
      val member = "outer"
      object InnerObject {
        val member = "inner"
        val ref1 = member
        val ref2 = this.member
        val ref3 = outer.member
    
        def method1 = {
          val member = "method"
          member
        }
        def method2 = {
          val member = "method"
          this.member
        }
        def method3 = {
          val member = "method"
          outer.member
        }
      }
    }
    
    scala> OuterObject.InnerObject.ref1
    res1: java.lang.String = inner
    
    scala> OuterObject.InnerObject.ref2
    res2: java.lang.String = inner
    
    scala> OuterObject.InnerObject.ref3
    res3: java.lang.String = outer
    
    scala> OuterObject.InnerObject.method1
    res4: java.lang.String = method
    
    scala> OuterObject.InnerObject.method2
    res5: java.lang.String = inner
    
    scala> OuterObject.InnerObject.method3
    res6: java.lang.String = outer
    
    0 讨论(0)
提交回复
热议问题