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);
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
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.
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