如何访问在 Trait 中声明的变量

How can I access a variable declared in a Trait

我已经在特征中声明了一个数组。如果我使用 extends 或 with 扩展我的 classes,我可以很好地使用在 traits 内声明的函数。但是,如果我声明了一个变量,我就无法访问它。所以,问题是如何从 class?

访问特征中定义的变量

示例:

trait X {
    val a = Array(100, 200, 300)
    ....
    def geta(): Array[Int] = this.a
    ....
}

object Y extends X {
    ....
    val x = a // Compiler error: Can't access a
    val y = geta() // This is fine
    ....
}

认为我明白你的问题...

如您所见,在 class 中访问特征函数的一种方法是扩展该特征。这也适用于变量:

trait TestTrait {
  val x = "I'm x"
}

class TestClass extends TestTrait {
  def printStuff = {
    println(x)
  }
}

new TestClass().printStuff // >>> I'm x

显然,如果您有任何 functions/variables 尚未分配给该特征内的值,则需要将它们分配给 class 内的值(函数也是如此):

trait TestTrait {
  val x = "I'm x"
  val y: String
}

class TestClass extends TestTrait {
  override val y = "I'm y"

  def printStuff = {
    println(x, y)
  }
}

new TestClass().printStuff // >>> (I'm x,I'm y)