Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
970 views
in Technique[技术] by (71.8m points)

scala - Disambiguate constructor parameter with same name as class field of superclass

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)
}

I found out that print(i) prints the constructor parameter i of Subclass(i : Int)

Now, my question is: in a situation like this, how do I access the field i of Superclass?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...