4

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);
blue-sky
  • 51,962
  • 152
  • 427
  • 752
  • 2
    possible duplicate of [What is the difference between a var and val definition in Scala?](http://stackoverflow.com/questions/1791408/what-is-the-difference-between-a-var-and-val-definition-in-scala) – om-nom-nom Dec 12 '12 at 16:15

2 Answers2

9

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
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • so it seems there are different levels of immutability and val is similar to a 'final' method in java in that its level of immutability is just that its reference to an object cannot be changed? A val is not as immutable as described at http://www.javapractices.com/topic/TopicAction.do?Id=29 unliess the developer codes the object that way ? – blue-sky Dec 12 '12 at 16:28
  • You need to make your referenced objects immutable (members declared via val). Of course those members need to be immutable too, and so on... – Brian Agnew Dec 12 '12 at 16:31
3

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.

Paolo Falabella
  • 24,914
  • 3
  • 72
  • 86