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

时间:2019-03-01 15:14:06

标签: scala traits

我在Trait中声明了一个数组。如果我使用extends或with扩展类,则可以使用在traits内部声明的函数。但是,如果声明一个变量,则无法访问它。因此,问题是如何从类访问特征中定义的变量?

示例:

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
    ....
}

1 个答案:

答案 0 :(得分:1)

思考我明白了你的要求...

您已经发现,访问类内部特征函数的一种方法是扩展该特征。这也适用于变量:

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

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

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

很显然,如果您尚未将任何函数/变量分配给该特征内的值,则需要将它们分配给类内的值(与函数相同):

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)