获取对具有冲突名称的外部函数的参数的引用 [英] Getting reference to a parameter of the outer function having a conflicting name

查看:33
本文介绍了获取对具有冲突名称的外部函数的参数的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑此代码:

trait A {
  def a : Int
}

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

问题很明显:def a0 = a 是典型的烦人的样板代码,当引入更多参数时,情况只会变得更糟.

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

我想知道是否有可能以某种方式在特征实例的声明中直接引用外部作用域的 a 变量,从而摆脱中间的 a0.

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.

请记住,不允许像更改特征那样更改函数的输入参数名称.

推荐答案

我认为没有直接方法可以做到这一点,因为它需要一些特殊的(假设的)标识符 这个方法.但是,根据您的上下文,可能可以通过以下两种方法来避免名称阴影:

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) 用实现类替换匿名类A:

(1) Replace anonymous class A with implementing class:

case class AImpl(a: Int) extends A

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

(2) 在抽象特征中定义 f 并为其使用具体实现:

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

这篇关于获取对具有冲突名称的外部函数的参数的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆