我为什么要这么做
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)
给出编译错误.
因为您没有在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)
| 归档时间: |
|
| 查看次数: |
411 次 |
| 最近记录: |