1
votes

Considering this trait 'Person' and this class '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

Using REPL (scala from command line, just open a terminal and type scala) I create the trait and the class. I have the following messages: -defined Trait Person -defined class PersonImpl

Then, still from the command line, I type:

  • val p: Person = new PersonImpl1("mario", "rossi", false)
  • println(p)
  • p.married=true
  • prinln(p)

I can clearly see that my person has been created and the var field married has been changed from false to true. Allright. Now I am repeating the same process just with another class and another trait:

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

As soon as I type the class into the command line I run into the error: 'variable x overrides nothing'

How can this be possible?

1
I forgot '=' in Element trait, which is: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 }Giacomo Bartoli
You've misspelled your setters, compare Element to your working example and you should see the difference.puhlen

1 Answers

1
votes

That's not the recommended way to do this in Scala - look into using case classes instead.

but to answer your q you should have def x_:(i:Int):Unit changed to def x_=(i:Int):Unit same for y