It took me a while too :)
You do not define the person val or var ", but create a new person method. Therefore, every time you call person , it creates a new instance of person , which will always have its variable for 0 This is a side effect of the fact that in Scala you no need to () call invisible methods.
def person = new Person("foo", 1)
roughly equivalent (in java code)
public Person person() { return new Person("foo", 1); }
whereas val person is what you want, i.e.
Person person = new Person("foo", 1)
(of course, this is not a real val , because Scala does not support these :))
and when you use person , what Scala understands is person() .
Just change def , which is used to define methods, to val or var , and everything will be fine :)
source share