Reputation: 53806
I'm setting a java Pojo instance variable to 'val' & changing its state after it's initialized. Will this cause any issues since its really a 'var' ?
val st = new Pojo();
st.setInt(0);
Upvotes: 4
Views: 707
Reputation: 25844
it's not a var
. Try doing st=new Pojo()
again and you will see that you can't reassign a new value to st (the compiler will complain error: reassignment to val
).
val
does not grant a "deep" immutability, just that the value initially set (which is just a reference to an object that can be mutable) can't be changed to a new reference.
Upvotes: 3
Reputation: 272257
It's still a val
. The reference can't be changed, but the object referred to can have its internal state mutated.
val
means you can't do this reassignment:
val st = new Pojo()
st = new Pojo() // invalid!
For this you need a var
:
var st = new Pojo()
st = new Pojo() // ok
Upvotes: 9