Scala 方法中变量名不明确
我看到了一些有关 Scala 和变量作用域的问题(例如 Scala 变量作用域问题)
但是,我无法让我的特定用例发挥作用。
假设我有一个名为 Repo 的特征:
trait Repo {
val source: String
}
然后我有一个方法来创建 Repo 的实现...
def createRepo(source: String) =
new Repo {
val source: String = source
}
当然我有两个正在使用的 source
变量,一个在方法级别,一个在方法级别内部Repo
实现。如何从我的 Repo
定义中引用方法级 source
?
谢谢!
I've seen some questions regarding Scala and variable scoping (such as Scala variable scoping question)
However, I'm having trouble getting my particular use-case to work.
Let's say I have a trait called Repo:
trait Repo {
val source: String
}
And then I have a method to create an implementation of Repo...
def createRepo(source: String) =
new Repo {
val source: String = source
}
Of course I have two source
variables in use, one at the method level and one inside of the Repo
implementation. How can I refer to the method-level source
from within my Repo
definition?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不确定这是否是规范的方式,但它有效:
或者,您可以给您的参数指定一个不冲突的不同名称。
或者,建立一个工厂:
Not sure if this is the canonical way, but it works:
Or, you could just give your paramenter a different name that doesn't clash.
Or, make a factory:
除了 Luigi 的解决方案之外,您还可以考虑将
Repo
从特征更改为类,In addition to the solutions of Luigi, you might also consider changing
Repo
from a trait to a class,