During a recent interview I had with a fairly reputable software company, I was tripped up trying to provide a valid explanation to a seemingly trivial Scala question. Consider the following:
case class Person(var age: Int)
def person = new Person(10)
person.age = 3
println(person)
This is what is returned by the println statement:
Person(10)
The question is why is this and what is happening when I assign 3 to person.age?
For this you need to understand the difference between val and def.
When you use def for any expression, it is evaluated every time it is being used. So, in this case when you do a person.age = 3 It will create a new instance of person object and assign 3 to its age, and when you do println(person) it will again instantiate a new person class and hence it prints Person(10).
So, If you have val instead of def like this: val person = new Person(10) and do
person.age = 3
println(person)
the output will be: Person(3) because, val is evaluated once. So, there will be only one instance of person in this case no matter how may times you use person.
Well,
def person = new Person(10)
is a function. That is, every time you call person, you create a new instance of Person. Thus, if we inline the function, your code would look like:
Person(10).age = 3
println(Person(10))
If you want to change the age of the person instance you created first, you need to capture that instance.
val p = person
p.age = 3
println(p)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With