Disambiguate constructor parameter with same name as class field of superclass

前端 未结 2 1384
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-21 10:10

When playing around with Scala I had a code like this:

class Superclass(var i : Int){}

class Subclass(i : Int) extends Superclass(0) {
   print(i)
}
<         


        
2条回答
  •  一向
    一向 (楼主)
    2020-12-21 10:36

    Type ascription can up-cast the type of this which effectively disambiguates the two identifiers

    class Subclass(i : Int) extends Superclass(0) {
      print((this: Superclass).i)
      print(i)
    }
    

    As a side-note, there also exists the following syntax that could be used in the case of method members (and which perhaps is not well-known)

    super[ClassQualifier]
    

    For example, consider the following

    trait A {
      def f = "A"
    }
    
    trait B extends A {
      override def f = "B"
    }
    
    class C extends A with B {
      println(super[A].f)
      println(super[B].f)
      println(f)
      
      override def f = "C"
    }
    
    new C
    // A
    // B
    // C
    

提交回复
热议问题