考虑到这个特征“Person”和这个类“PersonImpl”:
trait Person {
def name: String
def surname: String
def married: Boolean
def married_=(state: Boolean): Unit
override def toString(): String = name + " " + surname + " " + married
}
class PersonImpl(override val name: String,
override val surname: String,
override var married: Boolean) extends Person
使用 REPL(命令行中的 scala,只需打开终端并键入 scala)我创建了 trait 和类。我有以下消息: -defined Trait Person -defined 类 PersonImpl
然后,仍然从命令行,我输入:
- val p: Person = new PersonImpl1("mario", "rossi", false)
- 打印(p)
- p.married=true
- 原则(p)
我可以清楚地看到我的人已经被创建,var 字段已经从 false 变为 true。好的。现在我用另一个类和另一个特征重复相同的过程:
trait Element {
def x: Int
def y: Int
def width: Int
def height: Int
def x_:(i:Int):Unit
def y_:(i:Int):Unit
override def toString(): String = x + " " + y + " " + width + " " + height
}
class GameElement(override var x: Int,override var y: Int,override val width: Int,override val height: Int) extends Element
一旦我在命令行中键入类,我就会遇到错误:'variable x overrides nothing'
这怎么可能?