本文介绍了Scala 变量范围问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Scala 语法问题 - 假设我有一个简单的依赖模式构造,如下所示

I have a scala syntax question - say I have a simple dependency pattern construct like the following

trait Master {
  val foobar

  object SubObject extends SubObject {
      foobar = foobar
  }
}

trait SubObject {
  val foobar
}

显然,这不会编译,因为参考foob​​ar = foobar模棱两可.

Obviously, this will not compile, since the reference foobar = foobaris ambiguous.

如何指定表达式的 RHS 应该引用 Master 的 foobar 变量?我应该了解this"或self"的某种特殊用法吗?

How do I specify that the RHS of the expression should reference Master's foobar variable? Is there some sort of special usage of 'this' or 'self' that I should know about?

推荐答案

我相信最简单的方法是使用自类型定义.除了一堆很酷的类型理论效果之外,您还可以使用自我类型为this"创建别名.(没有测试过)

I believe the easiest way is to use a self-type definition. In addition to a bunch of cool type-theoretic effects, you can use a self-type to create an alias for "this". (Haven't tested this)

trait Master {
  master =>
  val foobar

  object SubObject extends SubObject {
      foobar = master.foobar
  }
}

trait SubObject {
  val foobar
}

这篇关于Scala 变量范围问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 05:09