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.2k views
in Technique[技术] by (71.8m points)

scala - Getting reference to a parameter of the outer function having a conflicting name

Please consider this code:

trait A {
  def a : Int
}

def f ( a : Int ) = {
  def a0 = a
  new A {
    def a = a0
  }
}

The problem is quite evident: def a0 = a is a typical annoying boilerplate code and the situation only worsens when more parameters get introduced.

I am wondering if it's possible to somehow get a direct reference to the a variable of the outer scope inside the declaration of the instance of the trait and thus to get rid of the intermediate a0.

Please keep in mind that changing name of input parameter of the function is not allowed as is changing the trait.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I don't think there is direct way to do that, because it would require some special (hypothetical) identifier thisMethod. However, depending on your context, the following two ways to avoid the name shadowing might be possible:

(1) Replace anonymous class A with implementing class:

case class AImpl(a: Int) extends A

def f(a : Int): A = AImpl(a)

(2) Define f in an abstract trait and use a concrete implementation for it:

trait F {
  def f(a: Int): A
}

object FImpl extends F {
  def f(a0: Int): A = new A { val a = a0 }
}

def test(factory: F): A = factory.f(a = 33)

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

...