为什么在Scala中扩展时必须重新定义特征中已定义的变量

Far*_*mor 1 scala

我为什么要这么做

trait Compiler {
  var printInstruction: String
}
class JavaCompiler extends Compiler {
  var printInstruction = "System.out.print(arg0);"
}
Run Code Online (Sandbox Code Playgroud)

代替

trait Compiler {
  var printInstruction: String
}
class JavaCompiler extends Compiler {
  printInstruction = "System.out.print(arg0);"
}
Run Code Online (Sandbox Code Playgroud)

什么时候

trait Compiler {
  var printInstruction: String
  def printInstruction: String
}
Run Code Online (Sandbox Code Playgroud)

给出编译错误.

Nic*_*las 8

因为您没有在trait中初始化变量Compiler.这意味着您希望任何扩展的人Compile定义一个行为类似于变量的东西.

例如,以下内容有效:

class Example extends Compiler {

   var _printInstruction = "foo"

   def pritnInstruction = "I don't care about setter"

   def pritnInstruction_=(pi: String) = _printInstruction = pi
}
Run Code Online (Sandbox Code Playgroud)

如果你想能够使用

class JavaCompiler extends Compiler {
  printInstruction = "System.out.print(arg0);"
}
Run Code Online (Sandbox Code Playgroud)

然后在Compiler特征中初始化你的var :

trait Compiler {
  var printInstruction: String = _
}
Run Code Online (Sandbox Code Playgroud)