1

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?

2
  • 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 } Commented Apr 11, 2017 at 17:29
  • 3
    You've misspelled your setters, compare Element to your working example and you should see the difference. Commented Apr 11, 2017 at 17:36

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.