Scala 方法中变量名不明确

发布于 2024-12-13 21:59:04 字数 545 浏览 0 评论 0原文

我看到了一些有关 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

玻璃人 2024-12-20 21:59:04

不确定这是否是规范的方式,但它有效:

def createRepo(source: String) = {
  val sourceArg = source
  new Repo {
    val source = sourceArg
  }
}

或者,您可以给您的参数指定一个不冲突的不同名称。

或者,建立一个工厂:

object Repo {
  def apply(src: String) = new Repo { val source = src }
}

def createRepo(source: String) = Repo(source)

Not sure if this is the canonical way, but it works:

def createRepo(source: String) = {
  val sourceArg = source
  new Repo {
    val source = sourceArg
  }
}

Or, you could just give your paramenter a different name that doesn't clash.

Or, make a factory:

object Repo {
  def apply(src: String) = new Repo { val source = src }
}

def createRepo(source: String) = Repo(source)
会傲 2024-12-20 21:59:04

除了 Luigi 的解决方案之外,您还可以考虑将 Repo 从特征更改为类,

class Repo(val source: String)
def createRepo(source: String) = new Repo(source)

In addition to the solutions of Luigi, you might also consider changing Repo from a trait to a class,

class Repo(val source: String)
def createRepo(source: String) = new Repo(source)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文