scala - 当存在同名本地成员时从外部范围访问值

标签 scala

假设我有一个具有属性 a 的特征:

trait TheTrait {
  def a: String
}

我有一个带有属性 a 的类,我想在其中匿名实例化该特征:

class TheClass {
  val a = "abc"
  val traitInstance = new TheTrait {
    def a = a   // I want to assign it to the `a` of TheClass here
                // but this way it doesn't work
  }
}

我怎样才能实现这个目标?

最佳答案

或者TheClass.this.a,或者在TheClass中给this一个别名(称之为self)是习惯)

class TheClass { self => 
  val a = "abc"
  val traitInstance = new TheTrait {
    def a = self.a   
  }
}

关于scala - 当存在同名本地成员时从外部范围访问值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8687010/

相关文章:

scala - 卡夫卡流: configuring `AdminClientConfig` or `ConsumerConfig` without overriding the values both

scala - 如何在 Play 框架中实现 POST-REDIRECT-GET

scala - sbt-idea 和 Idea sbt 插件的作用

list - 在列表中查找不在第二个列表中的元素(在scala中)

scala - 如何在现有的 SBT scala 项目中互操作 kotlin 代码

scala - 在spark/scala中给出重复值的唯一标识符

scala - 如何处理scala中外部命令的用户交互

html - Play 框架中如何使用 IF 语句让 CSS 仅用于一页

json - 在 Scala 中将 JSON 转换为 CSV?

java - 如何在文本文件中查找键并使用 Spark 和 JSON 将它们与另一个文件进行比较