Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...