Scala:如何从一个对象访问一个阴影函数变量 [英] Scala: How to access a shadowed function variable from an object

查看:114
本文介绍了Scala:如何从一个对象访问一个阴影函数变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做以下工作:

I would like to make the following work:

def foo(x:Int = 1) = {
  object obj {
    val x = foo.this.x
  }
}

但我不知道如何从对象中引用x。这可以在没有重新命名x的情况下完成吗?

But I don't know how to reference x from within the object. Can this be done without renaming x in one of the two spots?

重命名变量可能并不容易,例如 foo

Renaming the variables may not be easy when, for example, foo is a widely used API function with x as a named variable, while obj extends a 3rd party trait that has x as an abstract member.

推荐答案

为什么不引入一个与<$ c具有相同值的新变量$ c> foo 的参数 x ,但没有影子?

Why not just introduce a new variable that has the same value as foo's argument x, but is not shadowed?

def foo(x: Int): Unit = {
  val foo_x = x
  object obj {
    val x = 13
    def doStuff: Unit = printf("%d %d\n", x, foo_x);
  }
  obj.doStuff
}

foo(42)

这篇关于Scala:如何从一个对象访问一个阴影函数变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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