Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to a variable assignment when I call a method that returns an instance of a case class holding the said variable?

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?

like image 500
nmurthy Avatar asked Apr 11 '16 05:04

nmurthy


2 Answers

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.

like image 179
curious Avatar answered Sep 29 '22 08:09

curious


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)
like image 30
Sascha Kolberg Avatar answered Sep 29 '22 07:09

Sascha Kolberg